我的父组件中有一个click事件需要从我的子组件调用一个特定的函数。任何帮助都会被贬低!
答案 0 :(得分:2)
您可以使用@ViewChild执行此操作:
使用类型选择器
@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();
}
}
你可以在这里阅读更多内容: Call child component method from parent class - Angular 在这里:https://angular.io/guide/component-interaction
答案 1 :(得分:-1)
export class ParentComponent {
@Output() public counter: number = 100;
public handleClick() {
this.counter += 1;
}
}
export class ChildComponent implements OnChanges {
@Input() public counter: number;
public ngOnChanges(changes: SimpleChanges): void {
const counterProp = nameof<ChildComponent>('counter');
if (changes[counterProp]) {
const count: number = changes.counterProp.currentValue as number;
console.log(`Count is now ${count}`);
}
}
}
export class ParentComponent {
private count: number;
private counter: BehaviorSubject<number>;
constructor(private counterService: CounterService) {
this.counter = this.counterService.getCounter().subscribe((count: number) => {
this.count = count;
});
}
public handleClick() {
this.counter.next(this.count + 1);
}
}
export class ChildComponent implements OnInit {
private count: number;
constructor(private counterService: CounterService) {
this.counterService.getCounter().subscribe((count: number) => {
this.count = count;
});
}
}
export class CounterService {
private counter: BehaviorSubject<number>;
constructor() {
this.counter = new BehaviorSubject<number>();
}
public getCounter(): BehaviorSubject<number> {
return this.counter;
}
}
export class ParentComponent {
private count: number = 0;
constructor(private counterService: CounterService) {
}
public handleClick() {
this.counterService.increaseCount(this.count + 1);
}
}
export class ChildComponent implements OnInit {
private count: number;
constructor(private counterService: CounterService) {
this.counterService.counter.subscribe((count: number) => {
this.count = count;
console.log(`Count is now ${count}`);
});
}
}
export class CounterService {
public counter = new EventEmitter<number>();
public increaseCount(count: number) {
this.counter.emit(count);
}
}