【问题标题】:Angular two way data binding with banana box syntax not working使用香蕉盒语法的角度双向数据绑定不起作用
【发布时间】:2020-05-31 01:28:31
【问题描述】:

我正在尝试进行双向数据绑定,以便子级可以在子级更改时更新父级中的属性 (file)。

父级中的值只是未定义的。我做错了什么?

在子组件中(<cb-drag-and-drop-file>):

@Output() public fileChange = new EventEmitter<File>();
private fileValue: File;

@Input()
get file() {
    return this.fileValue;
}

set file(value) {
    this.fileValue = value;
}

private setDocument(uploadedFile: File): void {
    if (this.isFilesizeValid && this.isFileExtensionValid) {
        this.file = uploadedFile;
        this.fileChange.emit(uploadedFile);
        this.isFileValidAndUploaded = true;
    }
}

private clearOldFileReference(): void {
    this.file = undefined;
    this.fileChange.emit(undefined);
}

在父组件ts文件中:

file;
ngOnInit() {
   interval(1000).pipe(mapTo(this.file), tap(x => console.log(x))).subscribe(console.log);
}

在父组件html文件中:

<cb-drag-and-drop-file fxFlex
                       [allowedFileTypes]="[FILE_TYPE_ENUM.Xlsx]"
                       [(file)]="file"
                       description="faslkdfjlsdkjf">
</cb-drag-and-drop-file>

当然,我不必在父级中强制设置文件,这似乎不是反应性的,这是我认为 Angular 使用事件发射器的目的吗?这也意味着我不能使用香蕉盒语法,不是吗?我已将fileChange 添加到父级,并且当我使用香蕉盒语法时它永远不会被触发。

【问题讨论】:

  • 能否请您为此问题创建 stackblitz 演示?
  • @yurzui 我实际上已经设法让它工作了here,但我不得不使用行为主题

标签: angular rxjs rxjs6


【解决方案1】:

模板带有“盒子里的香蕉”符号(“Das Runde muss ins Eckige”):

<your-comp [(file)]="file" ...

YourCompComponent:

@Input('file')
file: string;

@Output('fileChange')
fileChanges$ = new EventEmitter();
...
this.fileChanges$.next('whatever'); 

替代:

private readonly bhs: BehaviorSubject<string> = new BehaviorSubject<string>('');

@Input('file')
file: string;

@Output('fileChange')
fileChanges$ = this.bhs.asObservable();
...
this.fileChanges$.next('whatever'); 

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2015-09-05
    • 2016-08-20
    • 2016-06-23
    • 1970-01-01
    相关资源
    最近更新 更多