如何解决使用查询参数初始化模板驱动的表单
我想使用查询参数值初始化模板驱动的表单。
直观地,您将创建表单并将其填充到ngAfterViewInit
上:
HTML
<form #f="ngForm">
<input type="text" id="firstName" name="fname" #fname ngModel>
<input *ngIf="fname.value" type="text" id="lastName" name="lname" ngModel>
<button type="submit">Submit</button>
</form>
组件:
@ViewChild('f') f: NgForm;
constructor(private route: ActivatedRoute) {}
ngAfterViewInit() {
const queryParams = this.route.snapshot.queryParams;
this.f.form.setValue(queryParams)
}
然后使用查询参数?fname=aaa&lname=bbb
现在,这种方法存在两个问题:
- 事实证明,这是行不通的,因为Angular需要another tick to register the form
-
setValue
不起作用,因为第二个ctrllname
在应用值时不存在。
这将需要我
- 增加一个额外的周期(Angular团队建议setTimeout @ console错误)
- 使用
patchValue
仅应用有效值,两次。
类似:
ngAfterViewInit() {
const queryParams = { fname: 'aaa',lname: 'bbb'};
// if we wish to access template driven form,we need to wait an extra tick for form registration.
// angular suggests using setTimeout or such - switched it to timer operator instead.
timer(1)
// since last name ctrl is only shown when first name has value (*ngIf="fname.value"),// patchValue won't patch it on the first 'run' because it doesnt exist yet.
// so we need to do it twice.
.pipe(repeat(2))
// we use patchValue and not setValue because of the above reason.
// setValue applies the whole value,while patch only applies controls that exists on the form.
// and since,last name doesnt exist at first,it requires us to use patch. twice.
.subscribe(() => this.f.form.patchValue(queryParams))
}
在实现这种不的过程中,是否有一种更简单的方法?在我看来,这样做会导致模板驱动的冗余。
附加:stackblitz Demo的“ hacky”灵魂
解决方法
使用[(ngModel)]可以尝试以下
sheet_read.loc[(sheet_read['Checklist'] == 'Log file validation') & (sheet_read['SITT'] == 'NaN'),'SITW'] = 'Mismatch'
然后使用表单组件
<form #heroForm="ngForm">
<div class="form-group">
<label for="fname">First Name</label>
<input type="text" class="form-control" name="fname" [(ngModel)]="queryParams.fname" required>
</div>
<div class="form-group" *ngIf="queryParams?.fname">
<label for="lname">Last Name</label>
<input type="text" class="form-control" name="lname" [(ngModel)]="queryParams.lname">
</div>
<button type="submit" class="btn btn-success">Submit</button>
您无需为每个表单控件声明。只需分配queryParams和ngModel即可处理其余部分。
,我们可以将[(ngmodel)]
与局部变量一起直接绑定到此处。
<form #f="ngForm">
<input type="text" id="firstName" name="fname" #fname [(ngModel)]="myfname">
<input *ngIf="fname.value" type="text" id="lastName" name="lname" [(ngModel)]="mylname">
<button type="submit">Submit</button>
</form>
一些component.ts
myfname:string;
mylname:string;
ngAfterViewInit() {
const queryParams = this.route.snapshot.queryParams;
myfname = queryParams.fname;
mylname = queryParams.lname;
}
我们还可以使用constructor()
代替ngAfterViewInit()
。
您可以使用[hidden]
代替ngIf
。这样,元素保留在dom中。另外我正在使用0毫秒的超时时间。
您可以使用QueryParamMap
中可观察到的ActivatedRoute
而不是快照,然后将参数映射到一个对象,并使用async
管道在模板中对其进行订阅
HTML
<h1 class="header">Hello There</h1>
<div class="form-container"*ngIf="(formModel$ | async) as formModel">
<form class="form" #ngForm="ngForm" (ngSubmit)="onFormSubmit()" >
<input [(ngModel)]="formModel.fname" name="fname">
<input [(ngModel)]="formModel.lname" name="lname">
<button type="submit">Execute Order 66</button>
</form>
</div>
<div class="img-container">
<img *ngIf="(executeOrder$ | async) === true" src="https://vignette.wikia.nocookie.net/starwars/images/4/44/End_Days.jpg/revision/latest?cb=20111028234105">
</div>
组件
interface FormModel {
fname: string;
lname: string;
}
@Component({
selector: 'hello',templateUrl: './hello.component.html',styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
@ViewChild('ngForm') ngForm: NgForm;
formModel$: Observable<FormModel>;
executeOrder$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(private activatedRoute: ActivatedRoute){}
ngOnInit(): void {
this.formModel$ = this.activatedRoute.queryParamMap.pipe(
map(paramsMap => {
const entries = paramsMap.keys.map(k => [k,paramsMap.get(k)]);
const obj = {}
for(const entry of entries){
obj[entry[0]] = entry[1]
}
// Should be working with es2020: return Object.fromEntries(entries)
return obj as FormModel
})
)
}
onFormSubmit() {
console.log(this.ngForm.value)
this.executeOrder$.next(true);
}
}
我已经在StackBlitz上创建了一个使用此方法的工作示例
https://stackblitz.com/edit/angular-ivy-6vqpdz?file=src/app/hello.component.ts
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。