[英]Object passed from parent component to child component always null
Refer to the code below, although I've initialized root component property frmeta
and added @Input
decorator on property meta
inside DformComponent
, the child DformComponent
still get a null from the root component inside DformComponent constructor
. 请参阅下面的代码,虽然我已经初始化的根组件属性
frmeta
并添加@Input
物业装饰meta
内DformComponent
,孩子DformComponent
还是从内部的根组件得到一个空DformComponent constructor
。 Is there anything wrong with my code? 我的代码有什么问题吗?
RootComponent 根组件
import { Component } from '@angular/core';
import { DformComponent } from './controls/DformComponent';
function containsMagicWord(c: any) {
if(c.value.indexOf('magic') >= 0) {
return {
noMagic: true
}
}
// Null means valid, believe it or not
return null
}
@Component({
selector: 'body',
templateUrl: 'RootComponent.html',
providers: [DformComponent]
})
export class RootComponent {
frmeta:any = {
phone:["123456789", containsMagicWord]
, ip:["192.168.137.169", containsMagicWord]
};
constructor(){
// this.frmeta has been initialized here
// this log is before the DformComponent constructor log
console.log(this.frmeta);
}
}
RootComponent.html RootComponent.html
<dform [meta]="frmeta"></dform>
DformComponent.ts DformComponent.ts
import { Component, Attribute, Input, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector:'dform',
templateUrl:'DformComponent.html'
})
export class DformComponent implements OnInit{
frmdata:any;
@Input() meta:any;
constructor(fb:FormBuilder, @Attribute('meta') meta:any){
// both meta & this.meta are always undefined & null
this.meta = meta;
console.log(meta);
debugger;
this.frmdata = fb.group(this.meta);
}
ngOnInit(){
}
dosubmit(event:any){
console.log(this.frmdata.value);
}
}
DformComponent.html DformComponent.html
<form [formGroup]="frmdata" (submit)="dosubmit($event)">
<inputmask formControlName="phone" mask="(___) ___ - ___"></inputmask>
<inputmask formControlName="ip" mask="___.___.___.___" ></inputmask>
<button type="submit">Post</button>
<pre>{{ frmdata.value|json }}</pre>
</form>
You cannot access the bound property in the constructor because it is not available yet. 您无法访问构造函数中的bound属性,因为它尚不可用。 Use the
ngOnInit
life cycle hook, and you'll be able to access it there. 使用
ngOnInit
生命周期钩子,您将可以在其中访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.