注意:我见过几个像我的标题这样的问题,但它们不能解决我的问题。比如:
Situation
在我的角度应用程序中有几个模板驱动的表单,有多个日期字段。我做了一个特殊的组件(DatePickerComponent),我把它作为子组件插入到所有这些表单中。
问题
组件中的变量是共享的。角可能实例化相同的对象,但我想要不同的实例!我很清楚如何做到这一点。
我认为是解决方案
这可能与您声明DatepickerComponent的位置有关。我在app.module.ts中声明了它,但是这为整个应用程序创建了一个实例。我不知道如何确保我的父组件被迫使用两个不同的子组件。
推理
我是在一个独立的组件中这样做的,因为我还没有日期选择器。现在它是一个带有模式表单验证的文本框。稍后我会做一些更好的事情(一个真正的日期选择器),我不想到处复制粘贴代码并犯错误。使用1组件,这是很容易做到的。
混凝土规范
import {Component, EventEmitter, Input, OnInit, Output} from "@angular/core";
import {ControlContainer, NgForm} from "@angular/forms";
@Component({
selector: 'app-datepicker-component',
templateUrl: './datepicker.component.html',
// Add viewProviders, so the input will be treated part of the form in the parent.
// https://stackoverflow.com/questions/39242219/angular2-nested-template-driven-form
viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class DatepickerComponent implements OnInit { // stuff }HTML文件:
<div class="form-group">
<label for="date" class="col-sm-4 control-label">{{ label }}</label>
<div class="col-sm-8">
<input type="text" name="date" id="date" class="form-control" [ngModel]="date" (ngModelChange)="dateChange.emit($event)"
#inputdate="ngModel" [required]="required" pattern="^(?:(?:31(\/|-|\.)(?:0[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)02\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)\d{2})$"/>
<span class="help-block" *ngIf="required && inputdate.invalid && inputdate.errors.required && (inputdate.dirty || inputdate.touched || triedSubmit)">Datum is verplicht.</span>
<span class="help-block" *ngIf="inputdate.invalid && inputdate.errors.pattern && (inputdate.dirty || inputdate.touched || triedSubmit)" >Datum moet formaat dd-MM-yyyy hebben.</span>
</div>
</div>在我使用的其他页面中:
<form>
<app-datepicker-component label="Actief vanaf" [(date)]="date1" [required]="true" [triedSubmit]="triedSubmit"></app-datepicker-component>
<app-datepicker-component label="Actief tot" [(date)]="date2" [required]="false" [triedSubmit]="triedSubmit"></app-datepicker-component>
</form>AppModule:
@NgModule({
declarations: [
AppComponent,
// stuff
DatepickerComponent
],
imports: [
// stuff
],
providers: [
// stuff],
bootstrap: [AppComponent]
})
export class AppModule { }出错的事情
date变量是共享的,因为使用的是同一个实例,我不想这样做。另外,如果验证触发了其中一个组件,它会认为其他组件无效(而它们不是)。
发布于 2018-04-08 10:44:58
实际上,它使用的不是同一个实例。问题是,它们都属于同一个form,并且对name使用相同的值。这将导致底层的角形物体将它们视为相同的。
您的选项是将它们放在单独的窗体中,或者使用不同的name值,可能是将名称作为输入传入。
https://stackoverflow.com/questions/49717003
复制相似问题