簡體   English   中英

使用ViewChild的子級到父級值訪問

[英]Child To Parent Value access using ViewChild

我已經閱讀了有關angular6的文章,其中有3種方法可以在子代與父代之間進行通信。如果錯誤,請演示1)輸出發射器2)使用viewchild 3)共享服務。

因此,在這里我需要了解如何將視子從孩子傳達給父母。

在下面的演示中,在子組件中創建了一個窗體,當子組件窗體有效時,該窗體應反映在父組件中。在此演示中,當組件加載到ngafterViewInit中時,請鈎住view子值,其工作原理與預期的一樣,但在鍵入時有些事情,子組件形式是有效的,以子形式啟用了按鈕,這些更改未反映在需要有效的父組件中,但未按預期工作。 誰能提供最好的方法?

父component.html

<h1> Parent Component</h1>

<button class="btn btn-danger " disabled="{{check}}">CheckParentEnable</button>
<div class="childComponent">
<app-child-component></app-child-component>
 k2
  </div>

父component.html

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  public check: boolean;
  @ViewChild(ChildComponent) myname: ChildComponent;


  constructor() {

  }
  ngAfterViewInit() {
    this.check = this.myname.loginForm.valid;
  }

}

Child.component.html

<h4>childComponentArea<h4>

  <h1>Welcome to child component</h1>


<form [formGroup]="loginForm">

<input type="email" formControlName="email" placeholder="Email" >

<button class="btn btn-danger" [disabled]="loginForm.invalid">Submit</button>
</form>

child.component.ts

import { Component, EventEmitter, Input,Output, OnInit } from '@angular/core';
import { FormControl, FormGroup,Validators } from '@angular/forms';
@Component({
  selector: 'app-child-component',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  loginForm:FormGroup;
  name:string ='sahir';
  constructor() { }

  ngOnInit() {
    this.createForm();
  }


 private createForm() {
    this.loginForm = new FormGroup({
      // tslint:disable-next-line
      email: new FormControl('', [Validators.required])

    });
  }

  k8

}

演示

您可能需要ngAfterViewChecked生命周期掛鈎來滿足您的需求。 父項的ngAfterViewInit不會為每個子組件值的更改而調用,而是會調用ngAfterViewChecked 另外,您還需要將父項中的change detection推入ViewChecked生命周期掛鈎中,否則您將在此行中遇到ExpressionChanged錯誤。

this.check = this.myname.loginForm.valid;

所以這是應該起作用的代碼

import { Component, ViewChild, AfterViewChecked, ChangeDetectorRef } from '@angular/core';
constructor(private cdr : ChangeDetectorRef) {

}

ngAfterViewChecked() {
     console.log('view checked')
     this._check = this.myname.loginForm.valid;
     console.log(this.myname.loginForm.valid);
     this.cdr.detectChanges();
}

還可以使用[disabled]="!check"而不是disabled="{{check}}" [disabled]="!check"

DEMO

暫無
暫無

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

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