简体   繁体   中英

Angular 8 : How to send the value from *ngfor to TS file

I have a code

<div *ngFor="let a of ABC">
{{a.error}}
</div>

Now I want to send the value of a to my TS file. I want to meet some expectation say 'a.error == true' then call some function and assign the value of a to some variable in ts file.

I hope it is clear. please ask if require more clarification

To communicate with the ts file as you say you just call a function which you declare

// In your ts.file

someFunction(a: any) {
  // some amazing stuff
  return 'Hello World';
}

and in your template

<div *ngFor="let a of ABC">
  {{ someFunction(a) }}
</div>

You should probably loop the variable ABC in the TS file before exposing it to the html template. Be aware of the fact that. if you call a function in the html, it will be evaluated many many times.

eg , the following will execute the someFunction many more times than you probably need.

//.html
<div *ngFor="let a of ABC">
{{someFunction(a)}}
</div>

I suggest creating the values you need to read in the html as a different var. for example.

//.ts
ERR: string[];
ngOnInit() {
  this.ERR = ABC.map(a => someFunction(a));
}

Then in the template just bind to the error array

//.html
<div *ngFor="let a of ERR">
    {{a}}
</div>    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM