[英]ERROR in : No provider for NgControl Angular AOT
我正在嘗試實現一個自定義ControlValueAccessor,因為Kara Erickson在最后一個Angular Connect https://youtu.be/CD_t3m2WMM8?t=20m22s上推薦。 將有效狀態從父組件傳遞給子組件。
app.component.html:
<app-country-select ngModel="model" name="country-select"></app-country-select>
國家select.component.html:
<select [formControl]="controlDir.control" #select placeholder="Country" i18n-placeholder (click)="onTouched()"
(change)="onChange($event.value)" [required]="required">
<option value="at">Austria</option>
<option value="au">Australia</option>
</select>
國家select.component.ts:
@Component({
selector: 'app-country-select',
templateUrl: './country-select.component.html',
styleUrls: ['./country-select.component.scss'],
})
export class CountrySelectComponent implements ControlValueAccessor {
@Input() required = false;
@ViewChild('select') select: HTMLSelectElement;
onChange: (value: any) => void;
onTouched: () => void;
constructor(@Self() public controlDir: NgControl) {
controlDir.valueAccessor = this;
}
...
}
完整的代碼存在於此: https : //github.com/maksymzav/ngcontrol 。
在JIT模式下運行代碼時,代碼運行正常。 我想因為在運行時它確實知道它使用了哪個控件:NgModel,或FormControlName,或FormControlDirective。 但是,當我使用ng build --prod
運行AOT構建時,它會失敗並顯示消息
錯誤輸入:沒有NgControl的提供者(“[錯誤 - >] <app-country-select> </ app-country-select>”)
有誰知道如何使這個構建成功? 謝謝。
您可以將@Optional()
裝飾器添加到您的controlDir
。
將依賴項標記為可選的參數元數據。 如果未找到依賴項,則Injector提供null。
在我的情況下,這解決了“無提供者”錯誤,我能夠成功編譯項目。
例:
constructor(
@Optional() // Add this decorator
@Self()
public controlDir: NgControl,
private stripe: StripeService,
private cd: ChangeDetectorRef
) {
// Better to add some checks here since controlDir can be null
if (controlDir) {
controlDir.valueAccessor = this;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.