How to send properties to a callback when #click is thrown on lit-element? - polymer

I am trying that when the click event is fired on a component in lit-element a callback is executed and it can receive a specific value:
this.list.map(item => html`
<button #click=${this._handleClick}></button>
`)
_handleClick(e){
console.log(item);
}
How can item be fetched in scope of _handleClick callback?

The easiest thing to do is create a closure for the click handler that captures the item:
this.list.map((item) => html`
<button #click=${() => this._handleItemClick(item)}></button>
`)
_handleItemClick(item) {
console.log(item);
}

Related

How can I indicate if a property of child component change in a method

The child component is app-google-maps-panel and have 2 property:
father component:
<div class="col-6">
<app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel>
</div>
And in parent have a method:
search() {
debugger;
this.locationIqService.getGeoByAddress(this.searchAdress).subscribe({
next: (res:Geo) => {
this.latitude=res.latitude;
this.longitude=res.longitude;
},
error: (error) => { console.log(`Error call LocationIQ ${error}`) },
complete: () => { }
});
}
How can actualize child component
Each time the parent component properties (longitude, latitude) are updated, the child component will be updated (actualized). So If it's not the case, you should check this this.locationIqService.getGeoByAddress(this.searchAdress)
Make sure this call is working and returning the appropriate values

Passing parameters to component in react through map React

I'm relatively new to React and Typescript.
I used a map function to create a list, li, in typescript. I tried passing a parameter to a function with info from the mapped object, but it doesn't seem to happen. it seems like the same argument is mapped to all the elements, like so:
state = {
groups: new Array<IGroups>(),
showGroup: false,
groupId: 0
};
showMembers(groupId: number) {
this.setState({ showGroup: true, groupId: groupId });
}
render() {
return (
<div>
<ul>
{this.state.groups.map(group => <li>{group.name} from {group.cityName} <button onClick={() => this.showMembers(group.groupId)}>For members</button></li>)}
{this.state.showGroup && <GroupMembers groupId={this.state.groupId}></GroupMembers>}
</ul>
</div>
)
}
the same "groupId" is being passed to the component every time.
what am I doing wrong?

How to insert typescript variable into html element submit method

Angular 8/Django 3 app. I am trying to add a variable that I retrieve from the server side client_secret to the stripe.confirmCardPayment() method. I keep getting the error Property 'client_secret' does not exist on type 'HTMLElement'.
checkout.component.ts
declare var Stripe: any;
export class CheckoutComponent implements OnInit {
client_secret;
constructor(){..}
ngOnInit() {
//THIS METHOD BELOW RETRIEVES 'client_secret'
this.getpaymentintent()
const stripe = Stripe('xxxx');
const paymentForm = document.getElementById('payment-form');
paymentForm.addEventListener('submit', function(ev) {
ev.preventDefault();
stripe.confirmCardPayment(this.client_secret, { //HOW DO I ADD 'client_secret' here?
payment_method:
... }}}
getpaymentintent(){..)}
}
html
<script type="text/javascript">
var stripe = Stripe('xxx'); // use your test publishable key
var elements = stripe.elements();
</script>
<form id="payment-form">
<div id="card-element"> </div>
<div id="card-errors" role="alert"></div>
<button id="submit">Pay</button>
</form>
To refer to member variables in a callback function, you could use the arrow function notation. Try the following
paymentForm.addEventListener('submit', (ev) => { // <-- arrow function here
ev.preventDefault();
stripe.confirmCardPayment(this.client_secret, {
payment_method:
... }}}

How to call this angular function on load

I am having a async function getDataStandard() which needs to be executed on click.I need to get the function automatically done without clicking. How to do that. Please help me as I am new to ionic.
async getDataStandard() {
let loading = await this.loadingCtrl.create();
await loading.present();
this.http.get('https://www.labourguide.co.za/LabourguideApi/index.php?q=mostRecentPublications').pipe(
finalize(() => loading.dismiss())
)
.subscribe(data => {
console.log("Testing ...............1");
this.data = data;
console.log(data);
console.log("Testing ..............2");
}, err => {
console.log('JS Call error: ', err);
});
}
This is the ionic part
<ion-button expand="block" (click)="getDataStandard()">getDataStandard</ion-button>
Call it on your ngOnInit
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
this.getDataStandard() ;
}
}
You can call this function from ngOnInit(){}.
Just call getDataStandard() in ngOnInit().
...
ngOnInit() {
this.getDataStandard();
}
...
angular has several lifecycle hooks they are just an method of the component that manage and run by angualr,there are three method that sutable for your need ngOninit ,ngAfterContentInit and ngAfterViewInit .
ngOnInit() {
this.getDataStandard();
}
ngAfterContentInit() {}
ngAfterViewInit() {}
all previes method will run once in sequence so if you want the function
will run as soon is possibe use ngOninit,or it you want to run after
the component fully initialized I will choses ngAfterViewInit.
Lifecycle Hooks 🌐

ReactJS component textarea not updating on state change

I'm trying to write a note taking/organizing app and I've run into a frustrating bug.
Here's my component:
import React from 'react';
const Note = (props) => {
let textarea, noteForm;
if (props.note) {
return (
<div>
<button onClick={() => {
props.handleUpdateClick(props.selectedFolderId, props.selectedNoteId, textarea.value);
}}>
Update
</button>
<textarea
defaultValue={props.note.body}
ref={node => {textarea = node;}}
/>
</div>
);
} else {
return <div></div>;
}
};
export default Note;
As it currently stands, whenever I switch between notes and rerender the note component with new content from the note.body prop, the textarea does not change and retains the content from the previous note. I've tried using the value attribute instead of the defaultValue attribute for the text area which doe fix the problem of the text area content not changing when the component rerenders, but when I do that I'm longer able to type in the textarea field to update the note
Doe anyone know a way I can both allow for users to type in the text field to update the note as well as have the textarea content change when I render different notes?
Thank you
The problem is that setting the value to your prop will cause all re-renders of the component to use the same prop, so new text is obliterated. One solution is to preserve the text in the local state of the component. To simultaneously listen to prop changes, you can set the state when you receive new props.
const Note = React.createClass({
getInitialState() {
return {
text : this.props.note.body
}
},
componentWillReceiveProps: function(nextProps) {
if (typeof nextProps.note != 'undefined') {
this.setState({text: nextProps.note.body });
}
},
render() {
if (this.props.note) {
return (
<div>
<button onClick={(e) => {
// Fire a callback that re-renders the parent.
// render(this.textarea.value);
}}>
Update
</button>
<textarea
onChange={e => this.setState({ text : e.target.value })}
value={this.state.text}
ref={node => {this.textarea = node;}}
/>
</div>
);
} else {
return <div></div>;
}
}
});
https://jsfiddle.net/69z2wepo/96238/
If you are using redux, you could also fire an action on the change event of the input to trigger a re-render. You could preserve the input value in a reducer.
Because componentWillReceiveProps is now unsafe Max Sindwani's answer is now a little out date.
Try these steps:
convert your component to a class
now you can include the shouldComponentUpdate() lifecycle hook
create your event handler and pass it into onChange
in <textarea> you can swap out defaultValue attribute for value (just use event.preventDefault() in the handler so that a user can continue to update text if required)
import React from 'react';
export class Note extends React.Component {
constructor(props) {
super(props);
this.state={text: this.props.note.body}
}
shouldComponentUpdate(nextProps) {
if(nextProps.note.body !== this.state.text) {
this.setState({text: nextProps.note.body})
return true;
}
return false;
}
updateText = (event) => {
event.preventDefault();
this.setState({text: nextProps.note.body});
}
render() {
if (this.props.note) {
return (
<div>
<textarea
onChange={this.updateText}
value={this.state.text}
name={'display'}
/>
</div>
);
} else {
return <div></div>;
}
}});