簡體   English   中英

訪問基於ngFor構建的角度組件中的單個對象

[英]Access a single object in an angular component built on ngFor

我有一個如下的角度組件,它在左側導航中顯示了來自后端的列表。

<div *ngFor="let navItem of navItemList" >
  <div style="height:24px; padding-top:7px">
   <a style="font-size: 10pt;color:#455A64; padding-left:18px;">
    <span
    style="font-weight: bold;"
    matTooltip="{{ navItem.name }} Reports"
    matTooltipPosition="right" >
    <i class="fa {{ navItem.icon }} fa-md" aria-hidden="true"></i>
    {{ navItem.name }}
    </span>
   </a>
  </div>
<mat-divider></mat-divider>
</div>

下面是.ts文件

@Component({
  selector: 'child-nav-list',
  templateUrl: './child.nav.list.component.html'
})
export class ChildNavListComponent {
  @Input() icon = '';
  @Input() navItemList: Array<any>
constructor() {
 console.log( this.navItemList);
 }
}

我在父組件中使用上述組件,如下所示

在TS文件中

 navItemList: Array<any> = [{name: 'Report1', icon: 'fa-file'}, { name: 'Report2',  icon: 'fa-file'}, { name: 'Report3',  icon: 'fa-file'}]

在html中

    <child-nav-list (click) = "reportsCLick($event)" [navItemList] = "navItemList$ | async" ></child-nav-list>

結果如下所示。

在此處輸入圖片說明

因此,當我單擊一個報表時,無法獲得被單擊的對象。 如何處理被點擊的對象?

在子節點上設置@Output EventEmitter

@Component({
  selector: 'child-nav-list',
  templateUrl: './child.nav.list.component.html'
})
export class ChildNavListComponent {
  @Input() icon = '';
  @Input() navItemList: Array<any>;
  @Output() emitter: EventEmitter;

  constructor() {
   console.log( this.navItemList);
  }

  onClickItem(item){
    this.emitter.emit(item);
  }
}

將帶有點擊事件的子HTML設置為8ytan說:

 <div *ngFor="let navItem of navItemList" (click)="onClickItem(navItem)">
 ...
</div>

發出事件時設置父組件函數;

    <child-nav-list (emitter) = "reportsCLick($event)" [navItemList] = "navItemList$ | async" ></child-nav-list>

您的(click)看起來像是整個列表一樣-而是將其放在導航列表中的項目上,而不是整個列表中。

<div *ngFor="let navItem of navItemList" (click)="onClickItem(navItem)">
  <div style="height:24px; padding-top:7px">
   <a style="font-size: 10pt;color:#455A64; padding-left:18px;">
    <span
    style="font-weight: bold;"
    matTooltip="{{ navItem.name }} Reports"
    matTooltipPosition="right" >
    <i class="fa {{ navItem.icon }} fa-md" aria-hidden="true"></i>
    {{ navItem.name }}
    </span>
   </a>
  </div>
<mat-divider></mat-divider>
</div>

然后在您的TS中:

@Component({
  selector: 'child-nav-list',
  templateUrl: './child.nav.list.component.html'
})
export class ChildNavListComponent {
  @Input() icon = '';
  @Input() navItemList: Array<any>
constructor() {
 console.log( this.navItemList);
 }

 onClickItem(item) {
  console.log(item);
 }
}

然后,您可以使用Output()將單擊的項目傳遞回父組件。

有幫助嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM