【问题标题】:Object passed from parent component to child component always null从父组件传递到子组件的对象始终为空
【发布时间】:2016-11-23 00:21:07
【问题描述】:

参考下面的代码,虽然我已经初始化了根组件属性frmeta并在meta里面的meta属性上添加了@Input装饰器DformComponent,但是子DformComponent仍然从里面的根组件中得到一个null 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);
  }
}

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>

【问题讨论】:

标签: angular data-binding angular2-components


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多