How can you reference template input variable '

2020-07-30 03:15发布

问题:

How can you reference template input variable hero from *ngFor="let hero of heros" inside Typescript?

I'm using a stateful component So code has this for the 'heros' equivalent in my code is:

   servers: Server[];

It is populated when screen first appears via ionViewDidLoad.

When I add the server via button at bottom, ionViewDidEnter calls same loading method to populate servers again.

When debugging I'm going via ionViewDidLoad path.

[

回答1:

Probably you can pass it inside a function

<div *ngFor="let hero of heros">
  <li click="print(hero)">{{hero}}</li>
</div>

and inside TS,

print(hero:Hero){
 console.log(hero.name);
}


回答2:

You are accessing the server variable outside of *ngFor loop that's why the value you got was undefined, because the server variable was unknown outside the ion-item. Try to insert the code ion-item-options inside the <ion-item> and it should work



回答3:

Per the Ionic documentation. on ionic-item-sliding you have to nest <ion-item-options> outside <ion-item>.

It ended up being a case of me putting the *ngFor on the wrong tag.

Thank you both @Sajeetharan and @brijmcq. Both your post sent me down the write path in the end.

Html

<ion-item-sliding *ngFor="let server of servers"> <! <<<-- Moved here -->
     <ion-item detail-push>
         <h1>{{server?.server}} </h1>
         <h2>{{server?.port}} </h2>
         <h2>{{server?.username}}</h2>
         <h2>{{server?.password}}</h2>
      </ion-item>
      <ion-item-options side="left">
         <button ion-button color="primary" 
                 (click)="editServerConfigPage(server)">
            <ion-icon name="redo"></ion-icon>
            Edit
         </button>
         <button ion-button color="danger">
            <ion-icon name="remove-circle"></ion-icon>
            Remove
         </button>
      </ion-item-options>
</ion-item-sliding>

Typescript

editServerConfigPage(server:Server):void {
    console.log('editServerConfigPage()', server);
    this.navCtrl.push('LoginDetailPage', {server: server});
}