Rag*_*rok 5 typescript angular
我试图将一个函数传递给子组件.传递函数工作正常.问题是,如果我想更改父组件的属性值,这不会起作用,因为'this'不是引用父组件,而是引用子组件(在我的情况下是DatagridComponent)
this似乎是问题的背景.请参阅以下代码中的注释.
父组件:
@Component({
selector: 'app-user-management',
templateUrl: './user-management.component.html',
styleUrls: ['./user-management.component.css'],
})
export class UserManagementComponent implements OnInit {
showUserDetails: boolean: false;
showUsergroupDetails = false;
onSelectUser() {
this.showUsergroupDetails = false;
this.showUserDetails = true;
console.log(this.showUsergroupDetails); // prints false, as expected
console.log(this.showUserDetails); // prints true, as expected
console.log(this); // prints DatagridComponent :(
}
Run Code Online (Sandbox Code Playgroud)
HTML,将onSelectUser作为函数传递:
<app-datagrid [onSelection]="onSelectUser"></app-datagrid>
Run Code Online (Sandbox Code Playgroud)
子组件:
@Component({
selector: 'app-datagrid',
templateUrl: './datagrid.component.html',
styleUrls: ['./datagrid.component.css']
})
export class DatagridComponent implements OnInit {
@Input() onSelection: () => {};
onSelectListItem(item: any) {
// some code
if (this.onSelection) {
this.onSelection(); // is executed, results see comments in parent component
}
}
}
Run Code Online (Sandbox Code Playgroud)
子组件的HTML:
<div *ngFor="let item of items" (click)="onSelectListItem(item)">
....
</div>
Run Code Online (Sandbox Code Playgroud)
我怎么能做到这一点?
Pan*_*kar 13
使用Output事件从子组件到父组件进行通信.使用Input属性绑定将数据传递parent给子
HTML
<app-datagrid (onSelection)="onSelectUser($event)"></app-datagrid>
Run Code Online (Sandbox Code Playgroud)
零件
@Component({
selector: 'app-datagrid',
templateUrl: './datagrid.component.html',
styleUrls: ['./datagrid.component.css']
})
export class DatagridComponent implements OnInit {
@Output() onSelection: EventEmitter<any> = new EventEmitter();
onSelectListItem(item: any) {
this.onSelection.emit(item);
}
}
//app-user-management method will receive item object
onSelectUser(item: any) {
//here you would have item object.
}
Run Code Online (Sandbox Code Playgroud)
另请参见组件交互
Mil*_*lad 12
问题更多是关于this上下文,您可以通过以下方式解决它:
onSelectUser = ()=>{ // note this part
this.showUsergroupDetails = false;
this.showUserDetails = true;
console.log(this.showUsergroupDetails); // prints false, as expected
console.log(this.showUserDetails); // prints true, as expected
console.log(this); // prints DatagridComponent :(
}
Run Code Online (Sandbox Code Playgroud)
我们使用粗箭头将当前组件的上下文保留在函数中
| 归档时间: |
|
| 查看次数: |
8438 次 |
| 最近记录: |