从父组件传递到子组件的对象始终为null

时间:2016-11-23 00:21:08

标签: angular data-binding angular2-components

请参阅下面的代码,虽然我已初始化根组件属性frmeta并在@Input内的meta属性DformComponent添加了DformComponent装饰器,但DformComponent constructor仍然从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); } } 内的根组件中获取null。我的代码有什么问题吗?

RootComponent

<dform [meta]="frmeta"></dform>

RootComponent.html

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.ts

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

DformComponent.html

    $name = $_POST['tekst'];
$file ="imgs/tbybc1.png";
header('Content-Type: image/png');
$im = imagecreatefrompng($file);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
$text = $name;
$font = 'fonts/Roboto-Thin.ttf';
imagettftext($im, 40, 0, 70, 215, $white, $font, $text);
//imagettftext($im, 20, 0, 260, 255, $white, $font, $data);
imagepng($im);
imagedestroy($im);

1 个答案:

答案 0 :(得分:1)

您无法访问构造函数中的绑定属性,因为它尚不可用。使用ngOnInit生命周期钩子,您将能够在那里访问它。