1
這裏有角新手。 在搜索了多個問題後,我找不到修復這個問題: 我試圖從模板中獲取子組件。它在AfterViewInit
上按預期工作,但試圖從其他組件中獲取時,它不起作用,返回undefined。你能幫我弄清楚我錯過了什麼嗎? 在此先感謝,祝你有美好的一天!Angular2 @ViewChildren在其他組件中返回undefined
tab.ts
@Component({
selector: 'tab',
template: `<products #productList></products>
`,
})
export class Tab implements AfterViewInit {
@ViewChildren("productList")
public products: QueryList<Products>;
title: string;
ngAfterViewInit(): void {
console.log(this.products.first.myForm.value);
}
}
tabs.ts
@Component({
selector: 'tabs',
template: `<md-tab-group>
<md-tab *ngFor="let tab of tabs let i=index" label="{{tab.title}}">
<tab></tab>
<button (click)="removeTab(tab)">Remove tab</button>
</md-tab>
</md-tab-group>
<button (click)="addTab()">Add new tab</button>`,
})
export class Tabs implements AfterViewInit {
tabs: Tab[] = [];
ngAfterViewInit(): void {
this.addTab();
}
addTab() {
var tabsLength=this.tabs.length;
if (tabsLength< 5) {
var tab = new Tab();
tab.title = "List " + (tabsLength + 1);
this.tabs.push(tab);
}
else {
console.log("CANNOT ADD NEW TAB, LIMIT REACHED");
}
}
removeTab(tab: Tab) {
var index = this.tabs.indexOf(tab)
if (tab.products.first.isDeletable()) {
this.tabs.splice(index, 1);
}
else {
console.log("CANNOT REMOVE TAB!")
}
}
}
products.ts
@Component({
moduleId: module.id,
selector: 'products',
templateUrl: '/app/Templates/products.component.html',
})
export class Products implements OnInit {
public myForm: FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit(): void {
this.myForm = this._fb.group({
products: this._fb.array([
this.initProduct(),
])
, grandTotal: ['']
});
this.myForm.controls['products'].valueChanges.subscribe((change) => {
this.myForm.controls["grandTotal"].setValue(this.computeTotal());
});
}
initProduct() {
return this._fb.group({
name: [''],
price: ['', Validators.required],
quantity: ['', Validators.required],
total: [''],
});
}
isDeletable(): boolean {
const grandTotal = this.myForm.controls['grandTotal'].value;
if (grandTotal > 0) {
console.log("CANNOT DELETE!")
return false;
}
return true;
}
}