[英]Angular 9, Binding an array as an @Input for child component is not working
由於某種原因,該數組未傳遞給子組件。 我錯過了什么?
我的子組件:.html
<ul>
<li *ngFor="let item of items">
<a (click)="itemHasBeenClicked(item)">{{item}}</a>
</li>
<ul>
.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-three-dots-menu',
templateUrl: './three-dots-menu.component.html',
styleUrls: ['./three-dots-menu.component.sass']
})
export class ThreeDotsMenuComponent implements OnInit {
constructor() { }
@Input()
public itemsList : string[];
ngOnInit(): void {
}
@Output()
itemClicked: EventEmitter<string> = new EventEmitter<string>();
itemHasBeenClicked(item)
{
alert(item);
this.itemClicked.emit(item);
}
}
父組件:.html
<app-three-dots-menu [itemsList]="menuItems"></app-three-dots-menu>
.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-users-table',
templateUrl: './users-table.component.html',
styleUrls: ['./users-table.component.sass']
})
export class UsersTableComponent implements OnInit {
constructor() { }
menuItems : string[] = ['New User', 'Refresh'];
ngOnInit(): void {
}
}
如果我在 ngOnInit 中初始化子組件(ThreeDotsMenuComponent)的 itemsList,它可以正常工作並顯示。 任何其他選項都不起作用,包括這一行
@Input()
public itemsList : ["item1","Item2"];
我確定我在某處遺漏了一件小事,我已經遵循了許多說明並在這里和其他論壇上閱讀了許多帖子,但仍然卡住了。
好吧,你必須使用=
而不是:
。 使用:
您正在定義屬性的類型,而不是實際值:
export class UsersTableComponent implements OnInit {
menuItems: string[] = ['New User', 'Refresh'];
}
在子模板 html 中,您指的是items
而不是itemsList
將子模板更改為:
<ul>
<li *ngFor="let item of itemsList">
<a (click)="itemHasBeenClicked(item)">{{item}}</a>
</li>
<ul>
看看以下內容: https://stackblitz.com/edit/angular-v8sk5f?file=src%2Fapp%2Fchild%2Fchild.component.html
在 ThreeDotsMenuComponent html 部分中,您指的是items
,但您需要使用itemsList
<ul>
<li *ngFor="let item of items"> <!-- here, use itemsList -->
<a (click)="itemHasBeenClicked(item)">{{item}}</a>
</li>
<ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.