Angular 角度2将函数var传递给不同的组件
我不熟悉angular 2,我有个问题。 我创建了一个名为ModalContent的组件,其功能之一是:Angular 角度2将函数var传递给不同的组件,angular,Angular,我不熟悉angular 2,我有个问题。 我创建了一个名为ModalContent的组件,其功能之一是: @Component({ selector: 'modal-content', templateUrl: './app/d-modal/d.modal.content.component.html', styleUrls: [ './app/d-modal/d.modal.content.component.css' ], providers: [InMemoryDataService],
@Component({
selector: 'modal-content',
templateUrl: './app/d-modal/d.modal.content.component.html',
styleUrls: [ './app/d-modal/d.modal.content.component.css' ],
providers: [InMemoryDataService],
})
export class ModalContent {
totalSelected:number;
addM() {
let selected = this.m.filter((x) => x["selected"]);
let totalSelected = selected.length;
console.log(totalSelected);
this.activeModal.close('Close click');
}}
如何将模态组件中的变量totalSelected
传递给一个名为form的完全不同组件中的函数,以使用它,如下所示:
@Component({
moduleId: module.id,
selector: 'form',
templateUrl: 'form.component.html',
styleUrls: [ 'form.component.css' ],
directives : [ModalContent],`
})`
export class FormComponent {
@ViewChild(ModalContent) childComp: ModalContent;
addMForm() {
const modalRef = this.modalService.open(ModalContent);
modalRef.componentInstance.name = 'World';`
this.childComp.addM();
for (var m = 0; m < totalSelected; m++)
{
let newGroup = new FormGroup({
A :new FormControl(),
B: new FormControl(),
C: new FormControl(),
D :new FormControl()
});
this.Form.controls.users.push(newGroup);
}}
}
@组件({
moduleId:module.id,
选择器:“表单”,
templateUrl:'form.component.html',
样式URL:['form.component.css'],
指令:[模块内容]`
})`
导出类FormComponent{
@ViewChild(ModalContent)childComp:ModalContent;
addMForm(){
const modalRef=this.modalService.open(ModalContent);
modalRef.componentInstance.name='World'`
this.childComp.addM();
对于(var m=0;m
我想实现的是根据模式组件中的选择数量在表单中创建多个字段,因此无论用户在模式组件中选择什么,我都希望捕获totalselected变量中的数字,并将其推送到表单组件中,并在(for)中使用它如果另一个组件是子组件,则可以使用
@input
装饰器在父组件和子组件之间传递数据。我会看看它应该会有帮助。此外,如果totalselected仅存在于您提供的函数范围内,您可能希望从函数返回它或在函数定义之前创建它。此外,由于您已经提到您的函数驻留在一个模态中,因此将模态作为另一个组件的子组件并使用@output
decorator可能更有意义
编辑--
你可以这样做
totalSelected: number;
addM() {
let selected = this.m.filter((x) => x["selected"]);
this.totalSelected = selected.length;
console.log(totalSelected);
this.activeModal.close('Close click');
}
现在,变量total selected在函数调用范围之外可用 另一个组件是子组件还是父组件?您可能正在考虑使用某种类型的服务您是否尝试使用事件发射器?您好。。我尝试了输入和查看工具,但仍然不起作用。我无法使用从父组件中的子组件中选择的totalselected。它总是告诉我这个.childComponent是未定义的,这是一个范围问题。在函数内部定义变量totalselected时,除非返回该值或在函数外部定义变量,否则只能从函数访问该变量。我将对我的答案进行编辑,让你明白我的意思。您是否可以对您的问题进行编辑,以显示您是如何执行输入/输出变量赋值的。我添加了编辑后的版本。。我希望你能找到解决办法你好,你找到解决办法了吗?