0

共享模型变量的格式与子组件不兼容,我应该如何处理转换而不弄乱我的应用程序模型?

import {Calendar} from 'primeng/primeng';

@Component({
    selector: 'foo',
    directives: [Calendar],
    template: `
    ...
    <p-calendar [(ngModel)]="model"></p-calendar>
    ...
`})
class FooComponent {
    // input format: "1970-01-01T00:00:00Z"
    // model is shared within the app
    // should stay in this format
    // Calendar doesn't support this format
    @Input() model; 


}
4

1 回答 1

0

我以一种我不太喜欢的方式解决了问题,欢迎任何更好的解决方案。谢谢。

@Pipe({
    name: 'iso2date'
})
export class Iso2Date {
    transform(value: any, args: Array<any>): string {
        return moment(value).format("YYYY-MM-DD");
    }
}

@Component({
    selector: 'foo',
    directives: [Calendar],
    pipes: [Iso2Date],
    template: `
    ...
    <p-calendar dateFormat="yy-mm-dd"
        [ngModel]="model | iso2date"
        (ngModelChange)="model=date2iso($event)"></p-calendar>
    ...
`})
class FooComponent {
    @Input() model; 

    date2iso(value) {
        var m = moment(value, "YYYY-MM-DD");
        return m.toISOString();
    }

}

ps:管道在动作中不起作用,否则以下内容会更清洁

@Pipe({
    name: 'date2iso'
})
export class Date2Iso {
    transform(value: any, args: Array<any>): string {
        return moment(value,"YYYY-MM-DD").toISOString();
    }
}

...
(ngModelChange)="model=(event | date2iso)"></p-calendar>
...

但是我收到以下错误:

Parser Error: Cannot have a pipe in an action expression at column 20 in [model=($event | date2iso)] in FooComponent@19:28 ("="yy-mm-dd"
                            [ngModel]="model | iso2date"
                            [ERROR ->](ngModelChange)="model=($event | date2iso)"
于 2016-06-24T09:35:45.577 回答