我被卡在今天部署在我的contact.component中的枚舉值中。它是一種形式的一部分。這裏是我是如何實現的枚舉:Angular 4.3 - 在子組件中實現枚舉的正確方法?
contact.component.ts(只有相關的代碼提取物)
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
//emum for contact list type
export enum ContactType {
'Select-One',
'Information-Request',
'Suggestion',
'CustomerService-Request',
'Quotation-Request',
'Complaint',
'UrgentCallback-Request'
}
...
export class ContactComponent implements OnInit {
//form property declarations
rForm: FormGroup;
post: any;
keys: any[]; //for enum
//variable declarations
contactType = ContactType; //for enum - assignment from above nested enum class
...
//use Constructor to specify form validation
constructor(private formBuilder:FormBuilder) {
//enum first then string fields
this.keys = Object.keys(this.contactType).filter(Number);
...
//method to post submitted contact form (here is where the back end service call is made to db)
addPost(post) {
this.contactType = post.contactType;
...
所以我對接觸組件的HTML類如下:
contact.component.html(僅提供相關代碼)
<div *ngIf="!firstName; else forminfo">
<fieldset>
<form id="online_contact_form" [formGroup]="rForm" (ngSubmit)=addPost(rForm.value)>
<div class="form-container">
<div class="row">
<h2>Online Contact Form</h2>
<!--Contact Type (Enum)-->
<p>
<label id="contactType">Contact Type:</label>
<select>
<option *ngFor="let key of keys" [value]="key">{{ contactType[key] }}</option>
</select>
</p>
<!--First Name-->
<p>
<label>First Name: <input type="text" formControlName="firstName" placeholder="Given/First Name here"></label>
</p>
<div class = "alert" *ngIf="!rForm.controls['firstName'].valid && rForm.controls['firstName'].touched">
{{ alertFirstName }}
</div>
<!--Last Name-->
...
<!--Template for form information-->
<ng-template #forminfo>
<div class="form-container">
<div class="row">
<h3>Many Thanks - Messsage is Sent - Details Are:</h3>
<h4>{{ contactType }}</h4>
<h4>First Name: {{ firstName }}</h4>
<h4>Last Name: {{ lastName }}</h4>
<h4>Email Address: {{ email }}</h4>
<h4>Contact Number: {{ contactNumber }}</h4>
<p>Comment: <br>{{ comment }}</p>
</div>
</div>
</ng-template>
因此,上面的樣式代碼在Chrome,Safari和Firefix上的聯繫表單中非常整潔地顯示了枚舉作爲下拉列表。我遇到的問題是選定的值,我似乎無法訪問在下拉列表中選擇的值,並將其添加到模板中(提交後),該模板會在點擊提交按鈕時顯示。有沒有一種方法.Selected(),我可以使用枚舉來讓他在Angular 4.3中選擇一個變量的值?
你打賭克里斯..我嘗試了一百萬的方式來讓它工作,並知道(像往常一樣..大聲笑)它會回到一兩行代碼......我通過submited枚舉類型'這個。 contactType [this.rForm.get('select')。value];'轉換爲字符串值並將其傳遞給post對象,並且它可以工作!還加上了'formControlName',因爲我昨天已經拿出了一百萬次,並將其恢復。 –
Enum現在適用於Chrome,Safari和Firefox,但在Chrome和Firefox中默認的「Select-One」值不會顯示爲默認下拉值。如果在完成前端之後Ive時間,將會重新訪問這個..感謝你們幫助兄弟!非常感激! –