我有一個表單,我希望在其中一個輸入中有一個默認值,該默認值是用戶的顯示名稱,但是,它沒有顯示,甚至在添加為默認值時也沒有顯示“hi”輸入,我不確定我應該做什么:
<form [formGroup]= "postForm" (ngSubmit)="onSubmit()" novalidate>
<div >
<label>Title</label>
<input type="text" formControlName="title" required>
</div>
<div >
<label>Content</label>
<input type="text" formControlName="message" required>
</div>
<div *ngIf="authService.userData as user" >
<input type="text" value="{{user.displayName}}" formControlName="owner" >
</div>
<div >
<button type="submit" [disabled]="!postForm.valid">Create</button>
</div>
</form>
這是與之相關的打字稿組件:
import { Component, OnInit } from '@angular/core';
import {AuthService} from "../shared/services/auth.service";
import { PostService } from '../post.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from "@angular/router";
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.scss']
})
export class CreatePostComponent implements OnInit {
public postForm: FormGroup;
constructor(public postService: PostService,
public formBuilder: FormBuilder,
public router: Router,public authService: AuthService){
this.postForm = this.formBuilder.group({
title: [''],
message: [''],
owner: [''] ,
date: new Date().toLocaleString()
})
}
ngOnInit(): void {
}
onSubmit() {
this.postService.createPost(this.postForm.value);
this.router.navigate(['list-posts']);
};
}
非常需要和感謝幫助,我還想指出,我曾嘗試將 diplayname 值直接放在 TypeScript 檔案中,但它不存在,它只能從 html 檔案中獲得。
uj5u.com熱心網友回復:
您不應該使用valueAngular 控制的表單,相反,初始值是您在 typescript 檔案中提供的值,因此,請從 html 中洗掉 value 部分,并在 typescript 檔案中替換為,owner: [''] ,甚至owner: this.authService.userData只是owner: 'hi'為了確保它作品。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485605.html
下一篇:每次單擊按鈕時如何更改文本?
