我尝试使用@ViewChild将一个组件动态注入父位置,但我收到错误:
无法读取属性' createComponent'未定义的
在ReferenceTableComponent组件上,我试图注入
@Component({
selector: 'app-reference-table',
templateUrl: './refTable.component.html',
styleUrls: ['./refTable.component.scss']
})
export class ReferenceTableComponent implements OnInit {
observable: Observable<any>;
@ViewChild('selectorTarget', {read: ViewContainerRef}) selectorTarget;
// colors
@Input() public datas: Array<string>;
public availableColors: Array<string>;
@Input() public nextRow: Array<string>;
//tailles
@Input() public headList: Array<string>;
public rows: Array<any> = [{}];
public rowIDs: Array<any> = [];
constructor(private _cr: ComponentFactoryResolver, private _viewContainerRef: ViewContainerRef) {
}
ngOnInit() {
this.computeAvailableColors();
}
addRow() {
console.log('this.availableColors 2: ', this.availableColors)
this.rows.push({});
}
computeAvailableColors() {
this.availableColors = _.concat([''], this.datas);
this.rowIDs = _.map(this.rows, 'color')
this.availableColors = _.difference(this.availableColors, this.rowIDs);
const select: ComponentRef<SelectOptionsComponent> =
this.selectorTarget.createComponent(
this._cr.resolveComponentFactory(SelectOptionsComponent)
);
select.instance.availableColors = this.availableColors;
select.instance.row = this.rows[0];
}
关于我的组件html
<td onSelectColor($event) #selectorTarget>
</td>
我试图注入的组件
@Component({
selector: 'kia-select-options',
template: `<div><select [(ngModel)]="row.color" (ngModelChange)="sendColorEvent(row, $event)">
// value is a string or number
<option *ngFor="let obj of availableColors">{{obj}}</option>
</select></div>`
})
export class SelectOptionsComponent {
// couleurs
@Input() public availableColors: Array<string>;
@Input() public row: {};
public color: string;
@Output()
public changed = new EventEmitter();
constructor(private injector: Injector) {
}
sendColorEvent(row, color) {
console.log(event)
this.changed.emit({ color: color, row: row });
}
}
知道ReferenceTableComponent是来自父组件使用的自动动态,并且它工作正常
@ViewChild('target', {read: ViewContainerRef}) target;
const factory = this.componentFactoryResolver.resolveComponentFactory(ReferenceTableComponent);
const ref = this.target.createComponent(factory);
答案 0 :(得分:8)
html = '''<div class="nav-wrapper">
<p class="navigation-links">
<span class="page-numbers current">1</span>
<a class="page-numbers" href="http://www.example.com/2/">2</a>
<a class="page-numbers" href="http://www.example.com/3/">3</a>
<span class="page-numbers dots">…</span>
<a class="page-numbers" href="http://www.example.com/6/">6</a>
<a class="next page-numbers" href="http://www.example.com/2/">Next →</a> </p>
</div>'''
bs = BeautifulSoup(html, "html.parser")
max_page = bs.find('span', {'class':'page-numbers dots'}).findNext().text
查询尚未在@ViewChild()
中提供。仅在调用ngOnInit()
时:
ngAfterViewInit()