首页 文章

将模型绑定到子组件[重复]

提问于
浏览
0

这个问题在这里已有答案:

我有3个组件 . '父母','孩子1'和'孩子2' . 在Parent组件的加载中,我在'Parent'中创建一个Model,并希望将该Model传递给子组件,然后子组件绑定到模型并更新父模型 .

例:

模型:

export interface ITemplateModel {
    id: string;
    name: string;
    lastModified: Date;
    status: string;
    templateHistory: string;
}

“父”:

templateModel = ITemplateModel();

从父HTML中的这一点来看,我不确定这是否正确但是显示了这个想法 .

'父HTML':

<app-child1 [(ngModel)]='templateModel'></app-child1>
<app-child2 [(ngModel)]='templateModel'></app-child2>

'Child1':

{{templateModel.name}}

'CHILD2':

<input [(ngModel)]="templateModel.status">

1 回答

  • 0

    不,我不认为你的方法是正确的 .

    如果需要将数据从Parent传递给子节点,则需要使用@Input() .

    Reference you can check for @Input()

    如果您需要将数据从Child传递给Parent,那么您需要使用@Output() .

    Reference you can check for @Output()

    这是如何在子元素上使用@Input和@Output参数的基本示例 .

    HTML:

    <app-child *ngFor="let item of items"  [name]="itemName"  (onSelect)="selectedItemName($event)"> </app-child>
    

    TS:

    export class ChildComponent {
      @Input()  name: string;
      @Output() onSelect = new EventEmitter<any>();
    
      sendSelect(selected: any) {
        this.onSelect.emit(selected);
      }
    }
    

相关问题