show full id shortened on button click -javascript-react - javascript

I can usage .slice method for cut a word. Here is example:
let UserID = 4EA1FC29-08D0-5A49-8754-DBD2691A0D36
let ShortUserID = UserID.slice(0, 14)
console.log(ShortUserID) here is console print: 4EA1FC29-08D0-
But my idea is click "..." button and open "selected row only" id.
Click a "..." button and show full id on just selected row(in this example clicking the button opens the id of all rows). My template is wrong. Here is my template:
Click button and show all ID's. Not "selected row". I want a click "..." button and show just selected row full id. I hope i could explain.
Here is my code template:
let ShortUserID = UserID.slice(0, 14)
const handleFullUserID = (index) => {
setIsClicked(!isClicked) //True-False Operator
}
if (isClicked) {
ShortUserID = UserID
}
return (
<tr key={index}>
<td>
{ShortUserID}(notfixed)
<button onClick={(index) => handleFullUserID(index)}>
...
</button>
</td>
</tr>
)

{isClicked ? UserID : ShortUserID}

Related

To highlight the selected row in mat-selection list and show its corresponding data by default

When we hover over the first column of the table a tooltip appears and then on clikcing on the button presnt in the tooltip mat dialog opens up.
The data loads but for the first time when the dialog opens up the row is not selected by default.
Note: (after the dialog has opened then on selecting any row its corresponding data loads and the row gets higlighted ,so this part works, but default highlighting of the left section row does not work when the popup opens for the first time)
The dialog contains 2 sections left and Edit json and. In the left whichever row is selected its corresponding data on the right side as json is shown.
alert-dialog.component.html
<div class="row align-items-center">
<div class="col-6 d-flex flex-column">
<span class="sub-section p-t-26 p-b-10">Predefined Alerts</span>
<div class="alert-select">
<mat-selection-list #preDefAlertList (selectionChange)="selectionChanged($event)">
<mat-list-option #option *ngFor="let preDef of data.data; let i = index" [value]="i" [ngClass]="option.selected ? 'selected-option' : ''">
{{preDef.alert}}
</mat-list-option>
</mat-selection-list>
</div>
<span class="sub-section p-t-10 p-b-10">Custom Alerts</span>
<div class="alert-select">
Lorem ipsum
</div>
</div>
</div>
alert-dialog.component.ts
export class AlertDialogComponent {
#ViewChild(MatSelectionList) preDefAlertList: MatSelectionList;
jsonform: FormGroup;
constructor( public dialogRef: MatDialogRef<AlertDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: DialogData, private alertService: AlertService,
private fb: FormBuilder) {
console.log(data);
this.jsonform = this.fb.group({
json: [data['data'][0].conditionals]
});
}
ngOnInit(){
this.jsonform.statusChanges.subscribe(() => {
if(!this.jsonform.valid && this.jsonform.dirty){
console.log("form is dirty and not valid")
}else{
console.log("form is dirty but valid")
}
});
this.preDefAlertList.selectionChange.subscribe((s: MatSelectionListChange) => {
this.preDefAlertList.deselectAll();
s.option.selected = true;
});
}
selectionChanged(event: MatSelectionListChange) {
this.jsonform.setValue({
json: this.data['data'][event.option.value].conditionals
});
}
onAddNewAlert(){
if(!this.jsonform.valid && this.jsonform.dirty){
console.log("final validation")
}
}
}
stackblitz link
https://stackblitz.com/edit/angular-mat-tooltip-uwsbqa?file=app/alert-dialog/alert-dialog.component.html
This below link is the older version before I did the changes where data was loading in mat dialog and the row was getting highlighted
https://stackblitz.com/edit/angular-mat-tooltip-qxxgcp?file=app%2Falert-dialog%2Falert-dialog.component.html
What I quickly can propose to you is to add ngAfterViewInit lifecycle hook and here mark the first option as selected.
ngAfterViewInit() {
this.preDefAlertList.options.first.selected = true;
}
EDIT - according to your comment
Please look at this example. Now I preselect element which was clicked and display its details on the right side.
https://stackblitz.com/edit/angular-mat-tooltip-ki4r2q?file=app/alert-dialog/alert-dialog.component.ts
try to use (selected) as input in mat-selection-list tag and then pass the parameter in the selectionChange Methode
If you want "mark as selected" a row, you can has a variable
selected:number=-1;
when you defined the mat-row, you add let i=index and you can change the style.background if i==selected, e.g.
<tr mat-row *matRowDef="let row; let i=index columns: displayedColumns;" [style.background-color]="i==selected?'red':null"></tr>
The last step if give value to the variable selected. For this, in a td, you can pass the row (futhermore the element)
<td mat-cell *matCellDef="let element;let i=index"
(click)="selected=i">
{{element.position}}
</td>
in this stackblitz if you "click" on "position", you see the row "selected".
In your case just in button you can add selected=i
<button (click)="selected=i;
onClick($event,(this.paginator.pageIndex == 0 ? i :
i + this.paginator.pageIndex * this.paginator.pageSize))">
Click
</button>
Don't forget if you want "des-select" equal the variable to -1
dialogRef.afterClosed().subscribe(result => {
this.selected=-1;
});

How to give unique id to table rows in react

I need to give different IDs to table rows, so that when I click on the first row, it'll show "selectedRow: 1" on console. Click on the second row, it'll show "selectedRow: 2"
Thanks in advance!
Here's my code:
<tbody>
{this.testData.map((item, i) => {
return (
<tr onClick={this.handler} key={i} >
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.address}</td>
</tr>
);
})}
</tbody>
handler=(e)=>{
let selectedRow = e.target.id //doesn't work
console.log("selectedRow:", selectedRow)
}
For that to work you would need to give every tr an id attribute, but it would be better if you just straight up pass that id to the function, like so:
<tr onClick={() => this.handler(item.id)}>
You can also use the index if the items don't have unique IDs.
Now the handler function would receive the id as an argument:
handler = (selectedRow) => {
console.log("selectedRow:", selectedRow)
}
For the tr onClick we can give our id as we like like <tr onClick={this.handler(item.id)}>
and our handler function will be high level function like below, then we don't require to create function each time
handler = id => e => {
console.log(id)
}
Sample code code from sandbox

How to manually add Items to MultiSelect in react-selectize?

I'm trying to add new value to react-selectize multiselect when the user clicks on a button (I use http://furqanzafar.github.io/react-selectize/#/) .
In JQuery I just call addItem(value, silent) on a button click.
for example in JQuery:
v.selectize.addItem("email#gmail.com");
In My code:
I created some MultiSelect component:
<MultiSelect
placeholder = "All Emails"
options = {this.state.emails.map(
source => ({label: source, value: source})
)}
onValuesChange = {value => this.onInputChange(value, "sources")}
/>
Then I have this button on the bottom of the page:
<button OnClick={this.addEmailValue("email#gmail.com")}></button>
When I click on the button it goes to:
addEmailValue(email){
//here I want to add the email as a item to the multiSelect
}
How can I add "email#gmail.com" to the MultiSelect as an item? (just like the JQuery example on top)
Thanks.
By the looks of things, you just need to update the 'emails' state by pushing the new email to it in your addEmailValue function. For instance:
addEmailValue(email) {
var emails = this.state.emails;
emails.push({
label: email,
value: email
});
this.setState({
emails: emails
});
}

Angular/Javascript - Hide button with id onclick

I have multiple buttons on one page, "Add to cart" buttons where each button has a unique id attribute.
I want to hide a particular button when the user clicks on it.
The issue:
What's happening currently is that when a user clicks on a button 1 it hides, then clicks on button 2 it hides but on the same time it shows button 1
The expected behavior:
When the user clicks on button 1 it should hide and keep hiding even after clicking on button 2
P.S. the information of the buttons (products) gets added to an array.
Current code:
Html:
<div *ngFor="let product of products; let i = index">
<div *ngIf="hideButton != i" [attr.id]="i" class="addButton" (click)="addToCart(product, i)">ADD</div>
</div>
JS
addToCart(itemDetails, index) {
this.hideButton = index;
}
You need an array of hidden buttons and you need to add the index to that array:
JS:
// at the top
hiddenButtons = [];
addToCart(itemDetails, index) {
this.hiddenButtons.push(index);
}
HTML:
<div *ngFor="let product of products; let i = index">
<div *ngIf="hiddenButton.indexOf(i) === -1" [attr.id]="i" class="addButton" (click)="addToCart(product, i)">ADD</div>
</div>
If you have a cart to which products are being added, you can look in the cart to check whether the product already exists in it, and use that to decide whether to display the ADD button.
If your product objects can have more properties to them, you can do away with indexes completely.
HTML
<div *ngFor="let product of products">
<div *ngIf="productInCart(product)" [attr.id]="product.id" class="addButton" (click)="addToCart(product)">ADD</div>
</div>
JS
productInCart(product) {
return this.products.findIndex(p => p.id==product.id)!=-1;
}
addToCart(product) {
this.products.push(product);
}
<div *ngFor="let product of products; let i = index">
<div *ngIf="!product.isHidden" [attr.id]="i" class="addButton" (click)="addToCart(product, i)">ADD</div>
</div>
In component
addToCart(itemDetails, index) {
itemDetails.isHidden = true;
this.products[index] = itemDetails;
}
Logic behind this is to create a new property in product when it clicked for add to cart. Initially there will be no property with name isHidden. SO, it will return undefined and undefined will treat as false.
I would suggest the following:
<div *ngFor="let product of products; let i = index">
<div *ngIf="!isInCart(product)" [attr.id]="i" class="addButton" (click)="addToCart(product, i)">ADD</div>
</div>
private hiddenProducts = new Set<FooProduct>();
products: FooProduct[] = [];
loadProducts(){
this.products = // some value
hiddenProducts = new Set<FooProduct>();
}
isInCart(product: FooProduct): boolean {
return this.hiddenProducts.has(product);
}
addToCart(product: FooProduct, index: number){
// optional: check if the element is already added?
this.hiddenProducts.add(product);
// rest of your addToCart logic
}
Why using a set instead of a simple array?
Performance: access time is constant.
Why not use the index as identifier?
Weak against list mutations (filter, reorder, etc)

react.js how to get prop form tree element

I am trying to make table cell editable after clicking on icon in another cell , for that I need to get index of element so the editor will open in the correct row , which icon belongs to.
My issue is that I dont know the way i should get the prop value of table DOM element here is code for for clearify
a part of dom tree generated with react:
<tbody>
{stepsDone.map(function(step,idx) {
let content = step;
const editing = this.state.editing;
if(editing){
content = (
<form onSubmit={this._save}>
<input type="text" defaultValue={step} />
</form>
);
}
return(
<tr key={idx}>
<td className="step" data-step={'step'+idx}>{content}</td>
<td className="icRow">
<Icon className="edit" onClick={this._showEditor} rownum={idx}/>
<Icon className="remove"/>
<Icon className="trash outline"/>
</td>
</tr>
)
},this)}
show editor function:
_showEditor(e){
this.setState({
editing:{
row:e.target.rownum
}
});
console.log(this.state.editing);
}
After execution of showedtior function console logs :
first click = null , which is normal i think
more clicks = undefined , and thats whats brings a trouble i want to receive idx from map function.
here is code from Icon.js
import React from 'react';
import classNames from 'classnames';
export function Icon(props) {
const cssclasses = classNames('icon', props.className);
return <i className={cssclasses} onClick={props.onClick}/>;
}
if you want to reveive the idx from the map function you should pass it to the function _showEditor so your code must be like this :
<Icon className="edit" onClick={this._showEditor(idx)}/>
and the function definition should be :
_showEditor = (idx) => (event) => {
this.setState({
editing:{
row:idx
}
});
console.log(this.state.editing);
}
or if you don't want to use the arrow functions for some reason, just replace
onClick={this._showEditor(idx)}
with
onClick={this._showEditor.bind(this,idx)}
and its definition becomes
_showEditor(idx){...}

Categories

Resources