2016-11-23 5 views
0

См ниже код, хотя я инициализируется корневой компонент свойство frmeta и добавил @Input декоратора на имущество meta внутри DformComponent, ребенок DformComponent еще получить нуль от корневого компонента внутри DformComponent constructor. Что-то не так с моим кодом?Объект передается от родительского компонента дочернего компонента всегда нуль

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> 
+0

Любая конкретная причина, по которой вы используете '@ Attribute' в конструкторе? –

+3

переместите свой код в ngOnInit. – Cleiton

+0

Возможный дубликат [Angular2 - невозможно получить доступ «Входы» от моего контроллера/конструктора] (http://stackoverflow.com/questions/33561845/angular2-cannot-access-inputs-from-my-controller-constructor) –

ответ

1

Вы не можете получить доступ связанного свойства в конструкторе, потому что он пока не доступен. Используйте крюк жизненного цикла ngOnInit, и вы сможете получить к нему доступ.

Смежные вопросы