角度前端 - 保存在数组中



我是Angular的新手。很抱歉,如果这是一件显而易见的事情,我应该知道。 我从后端获取了一个 String[],我想通过在前端的 mat-form-field 中键入它们来保存其中的各种字符串。 不知何故,更改不会显示在数据库中。 所有其他字段(仅请求字符串(工作正常。所以我想我在我的 html 中做错了什么

这是我的 HTML:

<div class="Placeholder" *ngIf="name$"> // this works, and i'm able to see my saved changes in the backend
<mat-form-field class="example">  
<input matInput [(ngModel)]="data$.lastname">
</mat-form-field>
</div>

<div  class="Placeholder"  *ngIf="name$" > //somehow I cannot "save" 
<mat-form-field class="example">
<input matInput [(ngModel)]="name$.abc" >
</mat-form-field>

这是我的名字.ts:

lastname: string;
firstname: string;
abc:string[];

我的保存按钮:

<button mat-button class="save" (click)="update()">save</button>

我的名字.服务.ts:

import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import {Observable, of} from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Name } from './name';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class NameService {
URL = 'placeholder';
ID: string;
constructor(private http: HttpClient, router: Router) { }
getData(headerID: string): Observable<Name> {
this.ID = headerID;       
return this.http.get<Data>(`URL`);
}
update(name: Name): Observable<Name> {                              
return this.http.put<Name>(`ID}`, name, this.httpOptions)
.pipe(catchError(this.handleError('update', name)));
}
}

和我的名字.component.ts

import { Component, OnInit, Pipe } from '@angular/core';
import { Name } from './name';
import { NameService } from './name.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
import { flatMap, subscribeOn } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-name',
templateUrl: './name.component.html',
styleUrls: ['./name.component.css']
})
export class NameComponent implements OnInit {
name$: Name;
update(): void {
this.nameService.updateName(this.name$)
.subscribe(name => this.name$ = name);
}

我希望这或多或少是可以理解的。我感谢任何形式的帮助!

您正在尝试错误地使用[(ngModel)]

你需要做的是

在组件中创建一个新的变量abcValue

abcValue: string;

然后在您的模板中,您需要将 [(ngModel(] 更改为

<input matInput [(ngModel)]="abcValue" >

然后,您将必须创建一个新函数,该函数将abcValue添加到$name.abc数组中

storeAbcValue() {
// check to see if abc exists / is array
if (this.name$.abc) {
// push the abcValue
this.name$.abc.push(this.abcValue);
} else {
// create new array and store in abc
this.name$.abc = [this.abcValue];
}
// clear abcValue
this.abcValue = null;
}

因此,在您的更新功能上,您将不得不执行以下操作

update() {
this.storeAbcValue();
// ...
}

最新更新