簡體   English   中英

從父組件傳遞到子組件的對象始終為null

[英]Object passed from parent component to child component always null

請參閱下面的代碼,雖然我已經初始化的根組件屬性frmeta並添加@Input物業裝飾metaDformComponent ,孩子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);
  }
}

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>

您無法訪問構造函數中的bound屬性,因為它尚不可用。 使用ngOnInit生命周期鈎子,您將可以在其中訪問它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM