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
. 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
<dform [meta]="frmeta"></dform>
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
<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. Use the ngOnInit
life cycle hook, and you'll be able to access it there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.