在Angular 2中,创建一个简单的应用程序但是当在选择列表的情况下使用DOM控件附加formBuilder时,第一个选项变为空白 - 即使我在formBuilder中提供了一些初始值,该值不是来自DOM元素
在FomBuilder之前
选择列表
Genral
LDAP
在FomBuilder之后
选择List
No选项最初出现
Genral
LDAP
File 1 - form.component.ts
import { Component } from '@angular/core';
import { FormBuilder, Validators, REACTIVE_FORM_DIRECTIVES, FormGroup, FormControl } from '@angular/forms';
@Component({
moduleId : module.id,
selector : 'login',
templateUrl : 'login.component.html',
directives : [ REACTIVE_FORM_DIRECTIVES ],
})
export class LoginComponent{
loginForm : FormGroup;
constructor(private _router:Router,private _fb:FormBuilder){
this.loginForm = _fb.group({
'username' : ['aa',[Validators.required]],
'password' : ['',[Validators.required]],
'type' : ['']
})
}
}
loginUser(){
console.log("Form is = ",this.loginForm.controls);
}
Run Code Online (Sandbox Code Playgroud)
文件2 …
我*ngFor在表中有一个子行组件,我需要用FormGroup包装.像这样的东西.
<tr [formGroup]='dependentForm'>
<td>
<input type="text" formControlName="first_name">
</td>
<td>
<input type="text" formControlName="last_name">
</td>
<td>
<input type="text" formControlName="dob">
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何从父模板加载组件,而不会弄乱标题列对齐.
我尝试过使用元素选择器和属性选择器,但似乎有一个障碍.如果我使用属性选择器,<tr dependent-row>并tr从子项中删除我然后无法在我的inputs 周围包装任何东西来分配一个formGroup或它弄乱了列.如果我使用一个元素选择器<dependent-row></dependent-row>并将其tr放在子组件内部,就像上面的示例一样,那只是通过列出所有tr内联来使表更糟糕.
我希望我已经很好地描述了我的问题.谢谢你的期待!
UPDATE
这是使用属性选择器的示例.组件中的tr标签dependent-row抛弃了表列,但我需要添加一些东西formGroup,所以我不知道如何正确处理它.
https://plnkr.co/edit/oXxkUGKtVp0T1u4Qz8AX?p=preview
这是使用元素选择器的替代方法.
我试图找出为ngModel实现自定义验证器逻辑的最简单方法.我有一个预定义的模型(接口),它存储当前数据,所以我不想处理新的FormGroup/FormControl(模型驱动)方法.
如果我已经拥有了我需要的所有数据,为什么要使用FormControls构建完全相同的模式?
这是我的代码(https://plnkr.co/edit/fPEdbMihRSVqQ5LZYBHO):
import { Component, Input } from '@angular/core';
export interface MyWidgetModel {
title:string;
description:string;
}
@Component({
selector: 'my-widget',
template: `
<h4 *ngIf="!editing">{{data.title}}</h4>
<input *ngIf="editing" type="text" name="title" [(ngModel)]="data.title">
<p *ngIf="!editing">{{data.description}}</p>
<textarea *ngIf="editing" name="description" [(ngModel)]="data.description" (ngModelChange)="customValidator($event)"></textarea>
<button (click)="clickEditing()">{{editing ? 'save' : 'edit'}}</button>
`
styles: [
':host, :host > * { display: block; margin: 5px; }',
':host { margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee; }',
'.ng-invalid { background-color: #FEE; }'
]
})
export class MyWidgetComponent {
@Input() …Run Code Online (Sandbox Code Playgroud) 如何使用嵌套字段创建表单,我知道formArray在angular2 RC中,但有点混淆如何正确使用它?假设我有一个这样的形式
// Main Form with formArray named as `global_modifier`
this.myForm = this._fb.group({
.......
name: ['', []],
global_modifier: this._fb.array([
this.initGlobalModifiers()
])
....
});
removeModifier(i: number) {
const control = <FormArray>this.myForm.controls['global_modifier'];
control.removeAt(i);
}
addModifier() {
const control = <FormArray>this.myForm.controls['global_modifier'];
control.push(this.initGlobalModifiers());
}
/*global_modifier function having nested fields named `items` .....*/
initGlobalModifiers() {
return this._fb.group({
.....
modifier_title: ['', []],
items: this._fb.array([
this.initItems()
])
.........
});
}
removeItem(i: number) {
const control = <FormArray>this.myForm.controls['items'];
control.removeAt(i);
}
addItem() {
const control = <FormArray>this.myForm.controls['items']; …Run Code Online (Sandbox Code Playgroud) 你好,我是Angular 2的新手,我正在寻找一种解决这个问题的好方法.所以我的用户对象里面包含另一个对象.该用户是一个界面:
export interface userModel{
name: string,
service: Service
}
Run Code Online (Sandbox Code Playgroud)
获得了一系列用于创建新用户的服务和表单.
<form #f="ngForm" (submit)="addUser(f.value,f.valid)">
<label for="name" class="col-sm-1 control-label">Name</label>
<div class="col-sm-4">
<input class="form-control" [(ngModel)]="userModel.name" #name="ngModel" name="name" ng-maxlength="49" />
</div>
<label class="col-sm-1 control-label">Service</label>
<select class="form-control" name="service" [(ngModel)]="userModel.service">
<option *ngFor='let service of services' [value]='service'>{{service.name}}</option>
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>
Run Code Online (Sandbox Code Playgroud)
如何将选定的服务对象传递给User对象?当我这样填充它时,我得到:
Object{
"name": "something",
"service": "[Object object]"
}
Run Code Online (Sandbox Code Playgroud)
所以显然我不能将对象作为值传递给select元素.然后我将该值设置为Service的id.修改界面:
export interface UserModel{
name: string,
serviceId: number
}
Run Code Online (Sandbox Code Playgroud)
在提交之前,我通过服务数组中的id找到Service对象,并将其设置在User对象中,其中包含Service对象.
userModel: UserModel;
user: User;
submit(model: UserModel ){
this.user = {
name : model.name,
service: …Run Code Online (Sandbox Code Playgroud) 我有一个注册表单,我想检查是否已经使用了用户名.为了达到这个目的,我现在正在使用承诺.我的注册组件如下所示:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserService } from '../shared/user.service'
@Component({
selector: 'app-auth',
providers: [],
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {
// Tabs for log in or sign up
tab = 'signup';
// Sign up form
signUpForm: FormGroup;
// Log in form
logInForm: FormGroup;
constructor(private formBuilder: FormBuilder, private ussr: UserService) {
this.signUpForm = this.formBuilder.group({
'username': [null, [
Validators.required, Validators.minLength(4), Validators.maxLength(12), this.ussr.getUserNameFromServer
]], …Run Code Online (Sandbox Code Playgroud) 我正在订阅valueChangesAngular 2(2.2.1)控件的可观察量.它AbstractControl在@angular\forms\src\model.d.ts中定义,并且它的文档字符串表明它将从UI以及程序化的更改:
/**
* Emits an event every time the value of the control changes, in
* the UI or programmatically.
*/
valueChanges: Observable<any>;
Run Code Online (Sandbox Code Playgroud)
如何对其进行过滤以仅向我提供UI的更改,而不是程序化的更改?
我认为布尔道具(原始的,脏的,触摸的等)对我没有帮助,因为即使控件被标记为脏 - 表示我想要捕获的UI的变化 - 可能还有进一步的程序化变化,我想忽略.
我有一个选择列表,我想将其初始化为从服务器返回的保存值。但是,无论我尝试什么,都无法使用所选的值。
我正在使用Angular 2.2.0和Reactive Forms。
这是选择列表的值列表。
private categoryList: ICategory[] = [
new Category({ id: 1, name: 'Cat 1' }),
new Category({ id: 2, name: 'Cat 2' }),
new Category({ id: 3, name: 'cat 3' })
];
Run Code Online (Sandbox Code Playgroud)
保存的值为:
{ id: 1, name: 'Cat 1' }
Run Code Online (Sandbox Code Playgroud)
使用FormBuilder创建表单
this.itemForm = this.fb.group({
name: [null, Validators.required],
description: [null, Validators.required],
weight: [null, Validators.required],
dimensions: [null, Validators.required],
category: [null, Validators.required]
});
Run Code Online (Sandbox Code Playgroud)
然后用保存的数据初始化
(<FormGroup>this.itemForm)
.setValue({
name: item.name,
description: item.description,
weight: item.weight,
dimensions: item.dimensions,
category: item.category
}, …Run Code Online (Sandbox Code Playgroud) 我已经运行了示例应用程序来学习角度2.在我的示例应用程序[(ngModel)]中无法正常工作.但当我删除方括号时(ngModel),屏幕正在加载,但双向绑定不起作用.
我应该做什么[(ngModel)]工作.
我有一个包含Fabrics数组的Angular2网格。这些织物具有诸如颜色或织物类型的特性。现在,网格已全部显示。我需要一些关于颜色和织物类型的复选框的数量以及旁边的数量。仅在单击“应用过滤器”按钮后,网格才会显示过滤的织物。但是,当选中一个复选框时,其他复选框的计数会更改。
例如
有人可以提供一些最有效的见解吗?我现在有所有数据。我将创建管道或过滤服务,还是拥有表单?
** 楷模 **
ProductConfigurationOption是选项选择的整体父项。例如 结构是ConfigurationOption。
配置选项选择是特定的结构,例如Tan Chenille。单个ConfigurationOptionChoice具有许多OptionChoiceProperty。
产品配置选项
import { ProductConfigurationOptionChoice } from './product-configuration-option-choice';
import { IProductConfiguratorOptionChoiceProperties } from '../Interfaces/iproduct-configurator-option-choice-properties';
import { IProductConfigurationOptionChoice } from '../Interfaces/iproduct-configuration-option-choice';
import { IProductConfigurationOption } from '../Interfaces/iproduct-configuration-option';
export class ProductConfigurationOption implements IProductConfigurationOption {
constructor(
public ConfiguratorID: number,
public OptionID: number,
public OptionName: string,
public OptionDescription: string,
public OptionSortOrder: number,
public SKUPartOrdinal: number,
public ProductConfigurationOptionChoice: IProductConfigurationOptionChoice[],
public OptionChoicesProperties: IProductConfiguratorOptionChoiceProperties[]
) {
}
}
Run Code Online (Sandbox Code Playgroud)
产品配置选项选择
import { ProductConfiguratorOptionChoiceProperties } from '../Models/product-configurator-option-choice-properties';
import { IProductConfiguratorOptionChoiceProperties …Run Code Online (Sandbox Code Playgroud) angular ×10
angular2-forms ×10
typescript ×3
asynchronous ×1
javascript ×1
rxjs ×1
validation ×1