将单个字符串推送到数组

时间:2019-03-27 04:52:20

标签: javascript angular typescript angular6

我有一个名为 UpdateContact 的组件,该组件显示在100 窗口中。该组件用于显示注入的对象,并将对该对象执行 PUT 操作注入的对象。组件代码如下:

HTML

dialog

TS

<form [formGroup]="updateForm">
    <mat-form-field>
        <input matInput [(ngModel)]="data.name"   placeholder="Name"  formControlName="Name">
    </mat-form-field>
    <mat-form-field>
        <input matInput [(ngModel)]="data.EMailAddresses"  placeholder="Email Address"  formControlName="Email">
        <mat-error *ngIf="updateForm.controls.email.hasError('email')>
             Please enter a valid email address
        </mat-error>
    </mat-form-field>
    <button mat-flat-button (click)="onClick()">Save</button>
</form>

联系人JSON

import { Component, Inject,  OnInit} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef, } from '@angular/material';
import { IContact } from 'src/app/models';
import { MyService } from 'src/app/services/my.service';

@Component({
  selector: 'app-update-contact',
  templateUrl: './update-contact.component.html',
  styleUrls: ['./update-contact.component.scss'],
})
export class UpdateContactComponent implements OnInit {
  public updateForm: FormGroup;
  public someContact: IContact

  constructor(@Inject(MAT_DIALOG_DATA) public data: IContact ,
              private fb: FormBuilder,
              public dialog: MatDialog,
              public myService: MyService,
              ) {} 

  public ngOnInit(): void {
    this.updateForm = this.fb.group({
      Name: [null],
      Email: [null,[Validators.email]],
    });
  }

  public onClick() {
    this.someContact= this.updateForm.value;
    this.someContact.EMailAddresses = [];
    this.someContact.EMailAddresses.push(this.updateForm.value.Email);  
    this.myService.updateContact(this.someContact, this.someContact.Id);
  }

}

服务文件

{
  "Id": "",
  "Name": "",
  "EMailAddresses": [""],
},

现在,当我按下 SAVE (保存)按钮而未在 Email (电子邮件)输入字段中进行任何更改时,我将无法执行 PUT 操作并获得此操作错误。

enter image description here

2 个答案:

答案 0 :(得分:0)

我已经解决了我的问题。由于属性 EMailAddresses 是一个array,所以我只需要将 EMailAddresses 转换为string并将其分配像这样的一个变量:

TS

public mail: string = this.data.EMailAddresses.toString();

,并且需要像这样在template中显示:

HTML

<mat-form-field>
         <input matInput [(ngModel)]="mail"  placeholder="Email Address"  formControlName="Email">
 </mat-form-field>

代替[(ngModel)]="data.EMailAddresses"

答案 1 :(得分:-3)

语法错误以初始化的形式出现:

  public ngOnInit(): void {
    this.updateForm = this.fb.group({
      Name: [null],
      Email: [null,[Validators.email],
    });
  }

在“电子邮件”表单控件中,缺少一个方括号!