我创建了一个子组件,它有一个我想要调用的方法。
当我调用此方法时,它只触发 console.log()
行,它不会设置 test
属性?
下面是我的更改的快速启动 Angular 应用程序。
家长
import { Component } from '@angular/core';
import { NotifyComponent } from './notify.component';
@Component({
selector: 'my-app',
template:
`
<button (click)="submit()">Call Child Component Method</button>
`
})
export class AppComponent {
private notify: NotifyComponent;
constructor() {
this.notify = new NotifyComponent();
}
submit(): void {
// execute child component method
notify.callMethod();
}
}
孩子
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'notify',
template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
test:string;
constructor() { }
ngOnInit() { }
callMethod(): void {
console.log('successfully executed.');
this.test = 'Me';
}
}
如何也设置 test
属性?
您可以使用 @ViewChild
来执行此操作以获取更多信息,请查看此 link
带类型选择器
子组件
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
父组件
@Component({
selector: 'some-cmp',
template: '<child-cmp></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild(ChildCmp) child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}
带字符串选择器
子组件
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
父组件
@Component({
selector: 'some-cmp',
template: '<child-cmp #child></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild('child') child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}
我认为最简单的方法是使用主题。在下面的示例代码中,每次调用“tellChild()”时都会通知孩子。
父组件.ts
import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
changingValue: Subject<boolean> = new Subject();
tellChild() {
this.changingValue.next(true);
}
}
Parent.component.html
<my-comp [changing]="changingValue"></my-comp>
Child.component.ts
...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
this.changing.subscribe(v => {
console.log('value is changing', v);
});
}
}
Stackblitz 上的工作示例
这对我有用!对于 Angular 2,在父组件中调用子组件方法
父组件.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child';
@Component({
selector: 'parent-app',
template: `<child-cmp></child-cmp>`
})
export class parentComponent implements OnInit{
@ViewChild(ChildComponent ) child: ChildComponent ;
ngOnInit() {
this.child.ChildTestCmp(); }
}
Child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-cmp',
template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> `
})
export class ChildComponent {
test: string;
ChildTestCmp()
{
this.test = "I am child component!";
}
}
ChildVM
的 ChildComponent
Angular – 在父组件的模板中调用子组件的方法
你有 ParentComponent 和 ChildComponent 看起来像这样。
父组件.html
https://i.stack.imgur.com/40D0r.png
父组件.ts
import {Component} from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() {
}
}
child.component.html
<p>
This is child
</p>
child.component.ts
import {Component} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
constructor() {
}
doSomething() {
console.log('do something');
}
}
发球时,它看起来像这样:
https://i.stack.imgur.com/rnywq.png
当用户关注 ParentComponent 的输入元素时,您想调用 ChildComponent 的 doSomething() 方法。
只需这样做:
给 parent.component.html 中的 app-child 选择器一个 DOM 变量名称(前缀为 # – hashtag),在这种情况下我们称之为 appChild。将表达式值(您要调用的方法)分配给输入元素的焦点事件。
https://i.stack.imgur.com/jixZC.png
结果:
https://i.stack.imgur.com/qC1Cg.gif
@ViewChild('appChild', { static: false }) appChild: ElementRef<HTMLElement>;
和以后使用 this.appChild.doSomething()
user6779899 的回答很简洁,更通用但是,根据 Imad El Hitti 的要求,这里提出了一个轻量级的解决方案。这可以在子组件仅与一个父组件紧密连接时使用。
父组件.ts
export class Notifier {
valueChanged: (data: number) => void = (d: number) => { };
}
export class Parent {
notifyObj = new Notifier();
tellChild(newValue: number) {
this.notifyObj.valueChanged(newValue); // inform child
}
}
Parent.component.html
<my-child-comp [notify]="notifyObj"></my-child-comp>
Child.component.ts
export class ChildComp implements OnInit{
@Input() notify = new Notifier(); // create object to satisfy typescript
ngOnInit(){
this.notify.valueChanged = (d: number) => {
console.log(`Parent has notified changes to ${d}`);
// do something with the new value
};
}
}
考虑以下示例,
import import { AfterViewInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { CountdownTimerComponent } from './countdown-timer.component';
@Component({
selector: 'app-countdown-parent-vc',
templateUrl: 'app-countdown-parent-vc.html',
styleUrl: [app-countdown-parent-vc.css]
})
export class CreateCategoryComponent implements OnInit, AfterViewInit {
@ViewChild(CountdownTimerComponent, {static: false}) private timerComponent: CountdownTimerComponent;
ngAfterViewInit() {
this.timerComponent.startTimer();
}
submitNewCategory(){
this.ngAfterViewInit();
}
}
Read more about @ViewChild here。
ngAfterViewInit()
,因为我们显式需要告诉 Angular 调用方法 startTimer()
,该方法位于组件 CountdownTimerComponent
中
父组件.html
<app-child #childComponent></app-child>
父组件.ts
@Component({
selector: 'app-parent',
templateUrl: './app-parent.component.html',
styleUrls: ['./app-parent.component.scss']
})
export class ParentComponent {
@ViewChild('childComponent', {static: false}) childComponent: ChildComponent;
anyMethod(): void {
childComponent.updateData() // updateData is a child method
}
}
child.component.ts
@Component({
selector: 'app-child',
templateUrl: './app-child.component.html',
styleUrls: ['./app-child.component.scss']
})
export class ChildComponent {
updateData(): void {
// Method code goes here
}
}
我有一个确切的情况,即父组件在表单中有一个 Select
元素,并且在提交时,我需要根据从选择元素中选择的值调用相关的子组件的方法。
父.HTML:
<form (ngSubmit)='selX' [formGroup]="xSelForm">
<select formControlName="xSelector">
...
</select>
<button type="submit">Submit</button>
</form>
<child [selectedX]="selectedX"></child>
家长.TS:
selX(){
this.selectedX = this.xSelForm.value['xSelector'];
}
儿童.TS:
export class ChildComponent implements OnChanges {
@Input() public selectedX;
//ngOnChanges will execute if there is a change in the value of selectedX which has been passed to child as an @Input.
ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
this.childFunction();
}
childFunction(){ }
}
希望这可以帮助。
不定期副业成功案例分享
Input
属性:一个可观察对象,孩子通过调用其 自己的 内部函数对其做出反应。见 user6779899 的回答