这是父HTML
<parent-component>
<child></child>
<button type="submit" [disabled]="!childForm.valid">
</parent-component>
这是儿童HTML
<child>
<form #childform=ngform>
<input required type="text">
</form>
</child>
我需要访问父组件
中的子窗体状态答案 0 :(得分:6)
儿童模板:
<form #childform=ngForm>
<input required type="text">
</form>
子组件:
export class ChildComponent implements OnInit {
@Output() validityChange = new EventEmitter<boolean>();
@ViewChild('childform') form: NgForm;
private validStatus: boolean;
ngOnInit() {
if (!this.form) return;
this.form.valueChanges
.subscribe(_ => {
if(this.validStatus !== this.form.valid) {
this.validStatus = this.form.valid;
this.validityChange.emit(this.form.valid);
});
}
}
父模板:
<child (validityChange)="childFormValid = $event"></child>
<button type="submit" [disabled]="!childFormValid">
父组件:
export class ChildComponent implements OnInit {
private childFormValid: boolean;
...
}
答案 1 :(得分:2)
可能你可以使用@ViewChild来实现:
子组件模板文件:
<form #form="ngForm">
<input type="text" ngModel required name="input">
</form>
并在子组件TS文件中使用@ViewChild,如下所示:
@ViewChild('form') form: NgForm;
父组件模板文件:
<button type="submit" *ngIf="childForm" [disabled]="!childForm.valid">Submit</button>
并在您的父组件TS文件中引用子组件:
export class ParentComponent implements AfterViewInit {
@ViewChild('child') child: ChildComponent;
public childForm;
ngAfterViewInit(): void {
this.childForm = this.child.form.form;
}
}
答案 2 :(得分:0)
使用输出
<child (myOutput)="myFunction($event)"></child>
在您的父组件中:
myFunction(event: Event) {
console.log(event); // hello world
}
在您的子组件中
import { Output, EventEmitter } from '@angular/core';
// ...
@Output() myOutput: new EventEmitter();
doSomething() {
thisMyOutput.emit('hello world');
}
答案 3 :(得分:0)
子组件
export class ChildparentComponent implements OnInit {
@Output() toParent = new EventEmitter<string>();
constructor() { }
onChange(value:string){
this.toParent.emit(value);
}
In Child Html
<app-childparent (toParent)="childValue = $event"></app-childparent>
在父母
中在父模板中访问此子值,例如{{childValue}}
相同
的工作示例https://rahulrsingh09.github.io/AngularConcepts/#/inout
其后端代码
https://github.com/rahulrsingh09/AngularConcepts/blob/master/src/app/parentchild/parentchild.component.html