在angular中,在添加子组件时,我们是否需要映射所有子Output变量



示例:父级-----

@Component({
selector: 'parent',
template: `<div> Test
<child [modal] = "parentModal"
(change) = "onChange($event)">
</child>
</div>`
})
export class ParentComponent {
parentModal;
ngOnInit() {
this.parentModal = "I am Parent";
}
onChange(event) {
console.log(event);
}
}

儿童----

@Component({
selector: 'child',
template: `<div>
{{modal}}
<a (click)="emitClick()"></a>
</div>`
})
export class ChildComponent {
@Input modal;
@Output change;
@Output open;

emitClick() {
this.change.emit();
}
}

我的代码可能有错误的语法。如果你发现一些,请纠正。

我的问题:

正如您所看到的,Parent并没有将Open参数传递给child。当点击A标签时调用emitClick函数会导致错误吗?

长话短说,不,你没有。但你的代码应该是:

父级:

@Component({
selector: 'parent',
template: `<div> Test
<child [modal] = "parentModal"
(change) = "onChange($event)">
</child>
</div>`
})
export class ParentComponent implements OnInit {
public parentModal = "I am Parent";
ngOnInit() {
}
onChange(event) {
console.log(event);
}
}

@Component({
selector: 'child',
template: `<div>
{{modal}}
<a (click)="emitClick()"></a>
</div>`
})
export class ChildComponent {
@Input() modal: string = '';
@Output() change = new EventEmitter<string>();
@Output() open= new EventEmitter<void>();

emitClick() {
this.change.emit('change');
}
}

最新更新