簡體   English   中英

嵌套組件上的Angular 2 Pass值

[英]Angular 2 Pass values on nested components

因此,在一個簡單的兩個傳遞數據的組件上,這應該很容易。 但就我而言,我使用的是第三方datepicker插件,因此由於我在不同形式的應用程序中有很多日期字段,因此我決定為datepicker創建一個組件,這樣就不必在每個應用程序中都重復配置查看我使用它。 現在的問題是我正在將模型傳遞給子組件,該模型也被傳遞給datepicker組件,如下所示:

家長component.ts

...
template: `<my-custom-datepicker-component [model]="model"></my-custom-datepicker-component>
<span>{{ model }}</span>
`
...
export class ParentComponent{
   model: any;
}

並在my-custom-datepicker.ts中

...
template: '<datetime [(ngModel)]="model"></datetime>'
...
export class MyCustomDatepickerComponent{
   @Input() model: any;
}

這是我正在使用的datepicker插件: https : //nkalinov.github.io/ng2-datetime/

我的問題是所選日期不會反映在父組件的模型上。 希望可以有人幫幫我。 提前致謝!

我定制的最新-picker.component.ts

template: '<datetime [(ngModel)]="model" 
      (ngModelChange)="dateChanged($event)"></datetime>'
...
export class MyCustomDatepickerComponent{
   @Input() date: any;
   @Output() dateChange = new EventEmitter<any>();
   // dateChanged will be called when datetime model changes
   // this will also trigger model
   dateChanged(date: any){
      this.dateChange.emit(date);
   }
}

parent.component.ts

...
template: `<my-custom-datepicker-component 
            [(date)]="programDate"></my-custom-datepicker-component>
<span>{{ programDate }}</span>
`
...
export class ParentComponent{
   programDate: any;
}

要么

...
template: `<my-custom-datepicker-component 
          (dateChange)="customComponentDateChanged($event)" [date]="programDate">
          </my-custom-datepicker-component>
<span>{{ programDate }}</span>
`
...
export class ParentComponent{
   programDate: any;
   customComponentDateChanged(date: any) {
     this.programDate = date;
   }
}

這僅說明:

  1. 子對父與EventEmitter的通信。
  2. 使用事件發射器進行雙向綁定

但是,您實際上是在說自定義日期選擇器時嘗試創建自定義表單元素 如果是這樣的話,那么這是一個有點復雜,因為你需要實現驗證和ngModel / ngControl / ControlValueAccessor作為解釋這里

話雖如此,如果您想向<datetime>添加一些新行為,則可以始終extend 原始組件 擴展它會使其功能保持完整(您將不得不提供新的模板/ css,因為@Component裝飾器不會被繼承),並且您可以添加自己的模板/ css。

為什么要在<datetime>之上創建自定義組件?

試試這樣

在my-custom-datepicker.ts中

@Input()模型:任意;

您可以在組件中使用this.model訪問模型

您是否將模型綁定到my-custom- datepicker.ts中的@Input屬性?

@Input() model: string;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM