[英]Angular 2: How to set default value of field from parent component back to child component?
I have the following scenario: childComponent is an angular material slide toggle that is used in different parts of my application. 我有以下情形:childComponent是一个有角度的材质滑动切换,用于我的应用程序的不同部分。 It is used in parentComponent1 and parentComponent2.
它在parentComponent1和parentComponent2中使用。 In parentComponent1 I want to set the default value of the slide toggle to be
true
but in parentComponent2 I want it to be false
. 在parentComponent1中,我想将幻灯片切换开关的默认值设置为
true
但在parentComponent2中,我希望它为false
。 How do I go about setting the default value of the slide toggle in the parentComponents? 如何在parentComponents中设置幻灯片切换开关的默认值?
I've tried the usual @Input recipe outlined in the angular docs ( https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding ), but no success. 我尝试了有角度的文档中概述的常规@Input食谱( https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding ),但没有成功。
Snippet of my child component: 我的孩子部分的代码段:
<mat-slide-toggle *ngIf="toggleFilterText"
class="example-margin"
[color]="color"
[(ngModel)]="checked"
[disabled]="disabled"
(change)="onToggleFilterChange(checked)">
{{toggleFilterText}}
and child ts 和孩子ts
@Input()
checked: boolean;
What do I do in my parent ts files to set the default value? 如何在我的父ts文件中设置默认值? Thanks.
谢谢。
I am assuming you need the value of 'checked' to be set. 我假设您需要设置“已检查”的值。 Add the input parameter to your HTML tag and set it to the desired value
将输入参数添加到HTML标记并将其设置为所需的值
<mat-slide-toggle *ngIf="toggleFilterText"
[checked] = "false"
class="example-margin"
[color]="color"
[(ngModel)]="checked"
[disabled]="disabled"
(change)="onToggleFilterChange(checked)" / >
It depends on how your parent components are set-up and if they are the same component. 这取决于您的父组件的设置方式以及它们是否相同。
If they are different components: 如果它们是不同的组件:
parent-component-1.ts
: parent-component-1.ts
:
public class Parent1Component {
public checked: boolean;
constructor() {
checked = true;
}
}
parent-component-2.ts
: parent-component-2.ts
:
public class Parent2Component {
public checked: boolean;
constructor() {
checked = false;
}
}
If they are the same component, you would need to do something like the following: 如果它们是相同的组件,则需要执行以下操作:
parent-component.ts
: parent-component.ts
:
public class ParentComponent {
@Input()
checked: boolean;
}
HTML: HTML:
<parent-component [checked]="true"></parent-component><!-- First -->
<parent-component [checked]="false"></parent-component><!-- Second -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.