【问题标题】:Can i send a object to a reactive form?我可以将对象发送到反应形式吗?
【发布时间】:2017-09-15 15:37:47
【问题描述】:

我想问是否可以将整个对象发送到角度 2 的反应形式。

这是我的表格:

this.parameterForm = this.fb.group({

  'name': ['', Validators.required],
  'description': "",
  'parameterType':''
});

第三个属性(parameterType)应该是一个对象。 (名称和描述只是纯字符串。

我的参数类型的 HTML 是(formControlName 用于映射它):

<label for="parameterType">Parameter Type</label>
<select id="parameterType" class="form-control" formControlName="parameterType">
  <option *ngFor="let parameterType of parameterTypes" [value]="parameterType">
    {{parameterType.name}}
  </option>

</select>

选择中的值是对象(在别处创建)。提交表单时,我想要 parameterType 对象。提交正在尝试将表单解析为一个名为 Parameter 的对象:

export class Parameter {

  public id: number;
  public name: string;
  public description: string;

  public parameterType? : ParameterType
} 

但是当我尝试在控制台中读取结果时,parameterType 只包含一个字符串“[Object object]”,看起来 parameterType 只是一个字符串,并且在提交表单时,该对象被转换为一个简单的字符串。

我的提交函数是这样的:

  onSubmit( {parameter}:{parameter: Parameter} ) {
    console.log(parameter);
  }

现在我只是这样做了,将参数类型发送到我发送 id 并通过服务我得到对象但这个解决方案不是很好。你知道我可以通过什么方式将对象传递给表单吗?

谢谢

【问题讨论】:

  • 尝试将参数作为 console.log(JSON.stringify(parameter));确保参数是否为对象
  • stringify 返回我这个:{"name":"entered name","description":"entered description","parameterType":"[object Object]"} 所以我认为它只是一个现在字符串。

标签: angular angular2-forms


【解决方案1】:

我认为您需要使用 [ngValue] 而不是 [value]。

【讨论】:

    【解决方案2】:

    你有几个选择:

    假设我有以下表格:

    user: FormGroup;
    
    this.user = this.formBuilder.group({
      account: this.formBuilder.group({
        email: ['', [Validators.required, Validators.pattern(EmailRegex)]],
        password: ['', Validators.required],
        passwordConfirm: ['', Validators.required]
      }, { validator: this.matchingPasswords('password', 'passwordConfirm') })
    });
    

    从那里,您可以使用 Object 设置表单的值:

    let user: SignUp = {
      account: {
        email: this.mail,
        password: '',
        passwordConfirm: ''
      }
    };
    this.user.setValue(user);
    

    Signup 是一个接口:

    export interface SignUp {
      account: {
        email: string;
        password: string;
        passwordConfirm: string;
      }
    }
    

    您可以通过这种方式从您的表单中创建一个新的Object

    let jsonResult = {
      email: this.user.value.account.email,
      password: this.user.value.account.password
    };
    

    或将表单用作接口中的对象(例如@Output):

    @Output() randomOutput= new EventEmitter<SignUp>();
    
    let data: SignUp = Object.assign({}, this.user.value);
    
    this.randomOutput.emit(data);
    

    【讨论】:

      猜你喜欢
      • 2014-11-14
      • 2019-10-12
      • 2018-10-25
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 2021-04-14
      相关资源
      最近更新 更多