代码之家  ›  专栏  ›  技术社区  ›  wheeeee

从复选框中获取值以在选中时传递到角度函数

  •  0
  • wheeeee  · 技术社区  · 2 年前

    我正在制作一个复选框列表,每个复选框都有不同的字符串值 heading , paragraph , list , table , visualtitle 。我觉得目前的方法 (change)="onChange('heading', $event.target.checked) 不是对该部分进行编码的正确方法,并且希望利用 name="annotationtype" 字段,这样我也可以在其他位置使用检查的值。如何获取此值?

    <form [formGroup]="form" (ngSubmit)="submit()">
        <div class="widget-container">
          <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('heading', $event.target.checked)" />Heading</label>
          <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('paragraph', $event.target.checked)" />Paragraph</label>
          <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('list', $event.target.checked)" />List</label>
          <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('table', $event.target.checked)" />Table</label>
          <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('visualtitle', $event.target.checked)" />Visual Title</label>
        </div>
    </form>
    
      onChange(name: string, isChecked: boolean) {
        if (!this.urlhash)
        {
          alert("Query URL cannot be empty!!!");
        }
        else
        {
          if (isChecked) {
            this.checkedAnnotations.push(new FormControl(name));
          } else {
            const index = this.checkedAnnotations.controls.findIndex(x => x.value === name);
            this.checkedAnnotations.removeAt(index);
          }
          var url = `/sd_api/htmlview/${this.urlhash}/highlighted.html?annotypes=${this.checkedAnnotations.value.join()}&datasource=${this.datasource}`;
          console.log(url);
          this.iframe = this.sanitizer.bypassSecurityTrustResourceUrl(url);
        }
      }
    
    0 回复  |  直到 2 年前
        1
  •  0
  •   godhar    2 年前

    最好的想法是利用Angular的做事方式。在这种情况下 Forms API 从…起 @angular/forms

    你可以利用这个api来完成大部分繁重的工作。绑定 formControlName FromGroup 对象,并使用您设置的关键点中的值。

    import { FormBuilder, FormGroup } from '@angular/forms';
    
    export class AppComponent {
      form: FormGroup;
    
      constructor(private formB: FormBuilder) {}
    
      ngOnInit(): void {
        this.form = this.formB.group({
          checkBox1: [false],
          checkBox2: [false],
        });
      }
    
      submit() {
        console.log(this.form.value);
      }
    }
    

    样板

    <form [formGroup]="form">
      <div class="widget-container">
        <input type="checkbox" formControlName="checkBox1" />Heading1
        <input type="checkbox" formControlName="checkBox2" />Heading2
        <div>
          <button type="button" (click)="submit()">Submit</button>
        </div>
      </div>
    </form>
    

    这样你就习惯了Angular在这些普通情况下使用的工具。