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