以下是我一直在使用的订阅和根据可观察数据更新响应式表单的过程。
也许有一种方法可以在不订阅可观察对象和更改值的情况下解决问题。
@Component({ selector: 'app-my-component', template: ` <form [formGroup]="myForm"> <input formControlName="name" /> <input formControlName="email" /> </form> `, }) export class MyComponent implements OnInit { myForm: FormGroup; constructor(private fb: FormBuilder, private ds: DataService) {} ngOnInit() { this.myForm = this.fb.group({ name: '', email: '', }); ds.data$.subscribe((data) => { this.myForm.setValue({ name: data.name, email: data.email, }); }); } }
P粉6048485882024-03-30 17:28:22
通常,消除订阅的一种方法是在包装器中使用异步管道
@Component({ template: `<app-user-form-component *ngIf="user$ | async as user" [user]="user"/>`, // closed tag is a new feature of angular selector: 'app-update-user-form-container' }) class UpdateUserFormContainer { user$ = inject(DataService).data$; }
表单本身可以在NgOnInit或NgOnChanges内处理用户更新(如果可能有多个更新,并且在这种情况下设置表单值很重要)
export class MyComponent implements OnInit { myForm = inject(NonNullableFormBuilder).group({ name: '', email: '', }); // this way form is not just FormGroup but the type is inferred from fields // i.e. this.myForm.getRawValue() would return you {name: string, email: string}; @Input({required: true}) user1: User; // required input is new feature of angular ngOnChanges(changes: SimpleChanges) { if('user' in changes) { this.myForm.setValue({ name: this.user.name, email: this.user.email, }) } } }
注意:此示例中使用了一些非常前沿的Angular功能。可以按照相同的模式进行操作,但不一定需要使用每个功能