data-binding - 在 Angular 2 中加载第一页时设置 [(ngModel)] 的值

标签 data-binding typescript angular angular2-ngmodel

我正在尝试创建一个简单的 select通过属性接收一些数据并呈现所需选项的组件。我计划在另一个组件的模板中使用这个选择组件,比如说 PageComponent的模板(page.template.html)。

我将 PageComponent 的一个变量绑定(bind)到 select组件使用 [(ngModel)] .选择一个选项后,变量的值会按预期更新,但我如何将其设置为在页面加载时指向第一个选项,而不触发 select 上的手动选择?组件?

这是代码。

在page.template.html中

<select ui-select 
        [options]="options" 
        [(ngModel)]="alertType"
        [defaultValue]="'Select an alert Type'">
</select>
{{alertType}} <!-- To see the value while debugging -->

在 page.component.ts 中,PageComponent

alertType:any;
options = [
    {id:1, value:"item-1"},
    {id:2, value:"item-2"},
    {id:3, value:"item-3"}
];

在select.component.ts中

import {Component, Input} from '@angular/core'

@Component({
  selector: '[ui-select]',
  template: `
    <option *ngIf="defaultValue" value="-1">{{defaultValue}}</option>
    <option *ngFor="let option of options" [value]="option.id">{{option.value}}</option>
  `
})
export class SelectComponent {
  @Input() options: any;
  @Input() defaultValue: string;
}

现在,{{alertType}} value 最初不显示任何内容,仅在从 select 中选择新选项时更新盒子。

我知道这是因为 alertTypePageComponent 中默认设置为未定义但我不知道如何在页面加载时将其设置为第一个选项值。

更新

原来的问题已经回答了,但我还有一个关于这个的问题所以更新了问题。

在更新的代码中,select组件接受 defaultValue来自模板的自定义属性并呈现条件 <option>对于该默认值。

现在,我怎么说如果 defaultValue已设置,alertType应该有那个值,否则它应该有 options 中第一项的值。列表。

P.S - 如果您对构建组件所用的方法有任何意见,请随时将其添加到答案中,因为这将帮助我学习。

最佳答案

所以您希望 alertType 应该设置为选定的值,无论它是来自您提供的 options 还是来自您的 defaultValue(首先选项)。

这可以通过使用 AfterViewInit Hook 来完成,

修改后的代码将是..

@Component({  
  selector: 'my-app',
  directives:[ 
    SelectComponent
  ],
  template : `<select ui-select
        [options]="options"
        [(ngModel)]="alertType"
        [defaultValue]="'Select an alert Type'" #mySelect>
</select>
{{alertType}}`
})
export class App implements AfterViewInit{
  @ViewChild('mySelect', {read: ViewContainerRef}) mySelect;
options = [
    {id: 1, value: "item-1", selected: false},
    {id: 2, value: "item-2", selected: true},//if all options will be false then defaultValue will be selected
    {id: 3, value: "item-3", selected: false}
];
alertType: any;

 ngAfterViewInit() {
    this.alertType = this.mySelect.element.nativeElement.value;
  }

}

我创建了一个 plunker , 检查这个!!

关于data-binding - 在 Angular 2 中加载第一页时设置 [(ngModel)] 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38197486/

相关文章:

javascript - 在 Angular 模板的样式标签中使用变量?

angular2 CLI HTTP 未找到错误

html - 更改 Angular Material 下拉列表和文本的默认位置

c# - 文本框的数据绑定(bind)

android - View :null 上的 View 标记不正确

wpf - 如何在 UserControl 和父窗口之间绑定(bind) WPF 命令

angular - Ion-list 是否应该自动在列表项上添加箭头?

typescript 中的递归未定义

c# - DataBinding 到 UserControl 内部的 UserControl

reactjs - react typescript : Object is possibly 'undefined'