Browse Source

表單值的存取,使用patchValue

master
HarveyChou 2 years ago
parent
commit
156303b3b5
  1. 12
      src/app/app.component.html
  2. 31
      src/app/app.component.ts

12
src/app/app.component.html

@ -1 +1,11 @@
查詢條件:<input type="text" [formControl]="condition"/>
<div [formGroup]="form">
<div>工作事項:<input type="text" formControlName="subject" /></div>
<div>工作內容:<input type="text" formControlName="content" /></div>
<div>
<button type="button" (click) = "onReset()">Reset</button>
<button type="button" (click) = "onSetValue()">Set Value</button>
<button type="button" (click) = "onPatchValue()">Patch Value</button>
</div>
</div>
<pre>{{form.value |json}}</pre>
<pre>{{form.dirty |json}}</pre>

31
src/app/app.component.ts

@ -14,24 +14,21 @@ import { debounce, debounceTime, distinctUntilChanged, filter, map } from 'rxjs/
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
readonly condition = new FormControl();
readonly stop$=new Subject<void>();
ngOnInit():void{
this.condition.valueChanges
.pipe(
debounceTime(500),
filter((condition:string)=> !!condition),
distinctUntilChanged(),
takeUntil(this.stop$)
)
.subscribe({
next:(condition) =>console.log(`查詢條件:${condition}`),
export class AppComponent {
constructor(private fb: FormBuilder) { }
readonly form = this.fb.group({
subject: this.fb.control(''),
content: this.fb.control(''),
});
}
ngOnDestroy():void{
this.stop$.next();
this.stop$.complete();
onSetValue(): void {
this.form.setValue({ subject: 'Task A', content: '' });
}
onPatchValue(): void {
this.form.patchValue({subject:'Task A'});
}
onReset():void{
this.form.reset({subject:'', content:''});
}
}
Loading…
Cancel
Save