带有香蕉盒语法的角度双向数据绑定不起作用

时间:2020-05-31 01:28:31

标签: angular rxjs rxjs6

我正在尝试进行两种方式的数据绑定,以便每当孩子对其进行更改时,孩子就可以更新父属性(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,并且在使用香蕉框语法时不会触发它。

1 个答案:

答案 0 :(得分:0)

模板,带有“框内香蕉”符号(“ Das Runde muss ins Eckige”):

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

您的CompComponent:

@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'); 
相关问题