我有以下场景:childComponent 是一个 Angular Material 滑动开关,用于我的应用程序的不同部分。它用于 parentComponent1 和 parentComponent2。在 parentComponent1 中,我想将滑动切换的默认值设置为 true
,但在 parentComponent2 中,我希望它为 false
。如何在 parentComponents 中设置滑动开关的默认值?
我尝试了 Angular 文档 (https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding) 中概述的常用 @Input 方法,但没有成功。
我的子组件的片段:
<mat-slide-toggle *ngIf="toggleFilterText"
class="example-margin"
[color]="color"
[(ngModel)]="checked"
[disabled]="disabled"
(change)="onToggleFilterChange(checked)">
{{toggleFilterText}}
和 child
@Input()
checked: boolean;
如何在我的父 ts 文件中设置默认值?谢谢。
最佳答案
这取决于您的父组件的设置方式以及它们是否是同一组件。
如果它们是不同的组件:
parent-component-1.ts
:
public class Parent1Component {
public checked: boolean;
constructor() {
checked = true;
}
}
parent-component-2.ts
:
public class Parent2Component {
public checked: boolean;
constructor() {
checked = false;
}
}
如果它们是同一个组件,您需要执行如下操作:
parent-component.ts
:
public class ParentComponent {
@Input()
checked: boolean;
}
HTML:
<parent-component [checked]="true"></parent-component><!-- First -->
<parent-component [checked]="false"></parent-component><!-- Second -->
关于javascript - Angular 2 : How to set default value of field from parent component back to child component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365972/