Arrays 角度前端-保存在阵列中
我是新手。很抱歉,如果这是显而易见的事情,我应该知道。 我从后端得到一个字符串[],我想通过在前端的mat form字段中键入来保存其中的各种字符串。 不知何故,这些更改不会显示在数据库中。 所有其他字段(仅请求一个字符串)工作正常。所以我想我在html中做了一些错误的事情 这是我的HTML:Arrays 角度前端-保存在阵列中,arrays,angular,typescript,Arrays,Angular,Typescript,我是新手。很抱歉,如果这是显而易见的事情,我应该知道。 我从后端得到一个字符串[],我想通过在前端的mat form字段中键入来保存其中的各种字符串。 不知何故,这些更改不会显示在数据库中。 所有其他字段(仅请求一个字符串)工作正常。所以我想我在html中做了一些错误的事情 这是我的HTML: <div class="Placeholder" *ngIf="name$"> // this works, and i'm able to see my saved changes in t
<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>
我的保存按钮:
<button mat-button class="save" (click)="update()">save</button>
我希望这或多或少是可以理解的。我感谢任何帮助 您试图错误地使用
[(ngModel)]
你需要做的是
在组件中创建一个新变量abcValue
abcValue: string;
然后在模板中,您需要将[(ngModel)]更改为
因此,在更新功能中,您必须执行以下操作
update() {
this.storeAbcValue();
// ...
}
我们需要看一些代码。您试图如何保存新数据?
输入
有一个值
属性,该属性采用字符串
。所以Angular接受数组并将其转换为逗号分隔的字符串。或者它不知道该怎么处理它,只是忽略了它。无论哪种方式,您都必须提供数组和字符串之间的转换。您是否尝试使用[(ngModel)]来设置数组字段?期望的结果是什么??您希望将字符串保存到数组中还是希望.abc成为字符串?我希望能够在名称数组中保存多个字符串(例如street+city)
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)));
}
}
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);
}
abcValue: string;
<input matInput [(ngModel)]="abcValue" >
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();
// ...
}