gpt4 book ai didi

angular - 使用查询参数初始化模板驱动的表单

转载 作者:行者123 更新时间:2023-12-03 16:48:17 30 4
gpt4 key购买 nike

我想初始化一个 模板驱动的表单 带有查询参数值。
直观地说,您将创建表单并在 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不会工作,因为第二个 ctrl,lname在应用这些值时不存在。

  • 这将需要我
  • 添加一个额外的周期(Angular 团队建议 setTimeout @ 控制台错误)
  • 使用 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)] 可以尝试以下

    <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>

    然后在表单组件中
    export class HeroFormComponent implements OnInit {
    @ViewChild("heroForm", null) heroForm: NgForm;
    queryParams={};
    constructor(private route: ActivatedRoute) {}

    ngOnInit() {

    this.queryParams = { fname: "aaa", lname: "bbb" };
    }
    }
    您无需为每个表单控件声明。只需分配 queryParams & ngModel 将处理其余的。

    关于angular - 使用查询参数初始化模板驱动的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63352647/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com