【问题标题】:Initialize template driven Form with query parameters使用查询参数初始化模板驱动的表单
【发布时间】:2020-08-11 06:28:51
【问题描述】:

我想用查询参数值初始化一个模板驱动表单

您可以直观地创建表单并将其填充到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&amp;lname=bbb

现在,这种方法有两个问题:

  1. 事实证明,这不起作用,因为 Angular 需要 another tick to register the form
  2. setValue 不起作用,因为第二个 ctrl lname 在应用值时不存在。

这需要我去

  1. 添加一个额外的循环(Angular 团队建议 setTimeout @ 控制台错误)
  2. 使用只应用有效值的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”灵魂

【问题讨论】:

标签: angular angular-forms


【解决方案1】:

用[(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 将处理其余的。

【讨论】:

    【解决方案2】:

    我们可以使用[(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>
    

    一些组件.ts

    myfname:string;
    mylname:string;
    
    ngAfterViewInit() {
        const queryParams = this.route.snapshot.queryParams;
        myfname = queryParams.fname;
        mylname = queryParams.lname;
    }
    

    我们也可以使用constructor() 代替ngAfterViewInit()

    【讨论】:

    • 感谢 tripathi,我宁愿不为每个表单控件定义变量(我想我在问题的底部说明了这一点),因为那样使用模板驱动根本没有意义
    • 您已经定义了一个用于选择表格的变量?你也可以定义单个变量model: { fname: string, lname: string }你想通过不定义变量来实现什么。? @斯塔姆
    • @Stavm - 后面给出的所有上述答案也使用了相同的 [(ngModel)] 技术。
    【解决方案3】:

    您可以使用[hidden] 代替ngIf。这样元素就保留在 dom 中。我也使用了 0 毫秒的超时时间。

    https://stackblitz.com/edit/angular-gts2wl-298w8l?file=src%2Fapp%2Fhero-form%2Fhero-form.component.html

    【讨论】:

    • 感谢您回答 Robin,您建议的方法不实用,它的基本意思是“呈现所有可能的形式,然后应用值”。拥有动态表单部分的整个想法是,当您不需要它时没有一个巨大的表单加上提交只发送该特定表单所需的表单值。
    • @stavm 并不理想,但它很容易。您还可以通过禁用不可见的控件来解决提交问题。禁用的值将不会被发送
    【解决方案4】:

    您可以使用来自ActivatedRouteQueryParamMap 可观察对象而不是快照,然后将参数映射到一个对象并使用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

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2021-11-24
      相关资源
      最近更新 更多