【发布时间】:2017-07-05 09:26:40
【问题描述】:
对于 Angular 2(和一般的 Angular)非常陌生,我遇到了我的同事的情况,他决定采用模板驱动方法,而我决定采用反应驱动方法。我们都创建了组件。他是一个搜索产品组件,我是一个信用卡组件。
它的作用和愿望
如果您从下拉框中选择信用卡,则会从搜索框中呈现我的组件(并在插入数字时进行验证)。
我希望将我的信用卡组件(作为孩子)中的数据绑定到他定义的 SearchProductModel 模型。 我看到了类似的东西,有点像我的问题,这里是帖子(Pass data from child to parent component Angular2)。
这些是组件和模板
creditcard.component.ts
@Component({
selector:'creditcard',
templateUrl:'./app/creditcard/creditcard.component.html'
})
export class CreditcardComponent {
creditForm: FormGroup
ccnumber = new FormControl('', [Validators.required, validateCreditcard]);
constructor(fb:FormBuilder){
this.creditForm = fb.group({"ccnumber":this.ccnumber})
}
search-product.component.ts
@Component({
selector:'search-product',
templateUrl:'./app/search/search-product.component.html'
})
export class SearchProductComponent{
products: Product[]
model = new SearchProductModel();
searchResult:string;
constructor(private searchProductService: SearchProductService){}
ngOnInit(): void {
this.searchProductService.getProducts().subscribe(products => this.products = products, error => console.log(error));
}
onSubmit(): void {
this.searchProductService.searchProduct(this.model).subscribe(result => this.searchResult = result,
error => console.log(error));;
}
搜索-product.component.html
<form (ngSubmit)="onSubmit()" #searchForm="ngForm" autocomplete="off">
<p>
<md-select placeholder="Product (optioneel)" [(ngModel)]="model.productId" name="product-id" id="product" style="width:250px">
<md-option *ngFor="let product of products" [value]="product.Id">{{product.Name}}</md-option>
</md-select>
</p>
<div [ngSwitch]="model.productId">
<p *ngSwitchCase="1">
<creditcard></creditcard>
</p>
<p *ngSwitchDefault>
<md-input-container style="width: 250px">
<input mdInput [(ngModel)]="model.productNumber" name="product-number" id="product-number" required/>
<md-error>productnumber required</md-error>
</md-input-container>
<button md-button type="submit" id="btn-zoek">Search</button>
</form>
creditcard.component.html
<form [formGroup]="creditcardForm">
<div class="form-group">
<md-input-container>
<input mdInput formControlname="creditcardnumber" id="creditcardnumber" name="creditcardnumber"/>
<div *ngIf="creditForm.get('creditcardnumber').dirty && creditcardForm.get('creditcardnumber').hasError('validCreditcard')">Not correct creditcard</div>
</md-input-container>
</div>
</form>
据我了解,混合模板驱动和响应式方法是不可取的,因此我将在未来对其进行重构。但是现在我想知道如何才能让我的信用卡输入进入他的 model.productId (参见代码)。 请耐心等待,我是这方面的新手,我只是很难理解它。
帮助非常感谢。
【问题讨论】:
标签: angular typescript angularjs-directive angularjs-scope components