![](/img/trans.png)
[英]Angular: why can't I use a method of my component as an obserable callback to update properties in the component?
[英]Why can't I pass arrow functions in the angular component properties
其他組件模板:
<app-search-bar [onSearch]="content => onSearch(content)"></app-search-bar>
錯誤:解析器錯誤:綁定不能包含 [content => onSearch(content)] 中第 10 列的賦值
應用搜索欄.component.ts:
...
export class SearchBarComponent implements OnInit {
searchText = '';
@Input() onSearch: (content: string) => void;
constructor() { }
ngOnInit(): void {
}
}
我是angular的新手,不知道原因,這是不正確的,以至於IDE無法知道組件傳遞什么屬性。 和reactjs的編程model相比,這個很不友好
模板解析器允許基本的 JavaScript 語法 - 它仍可用於構建復雜的語句,但建議保持基本
如果您需要引用更復雜的語法,例如箭頭 function,只需將其分配給組件上的屬性並在模板中引用該屬性
angular中組件之間的通信可以通過以下幾種方式進行:
讓我們的組件保持如此簡單,我們假設您的應用程序不是 state 的主題,以使用NGRX工具(推薦用於大型和復雜的 angular 應用程序)。
首先,您的組件“app-search-bar”應該顯示例如帶有按鈕的輸入文本,單擊該按鈕將在父組件中觸發一個事件,以便獲得過濾的搜索結果以顯示在頁面中:
export class SearchBarComponent implements OnInit {
searchText = '';
@Output() onSearch = new EventEmitter<boolean>();
constructor() { }
...
fireSearch() {
this.onSearch.emit(this.searchText);
}
}
而組件“app-search-bar”的 html 如下所示:
<input type="text" [value]="searchText">
<button (click)="fireSearch()">Search</button>
最后,在父容器中,您必須使用提供的內容檢查“onSearch”事件以過濾數據並在頁面中顯示它們:
<app-search-bar (onSearch)="onSearch($event)"></app-search-bar>
<table>
<thead>
<tr>
<th>First column</th>
</tr>
</thead>
<tbody *ngIf="data">
<tr *ngFor="item in data">
<td>{{ item.columnValue }}</td>
</tr>
</tbody>
</table>
而在父組件的 typescript class 中,你必須像這樣實現事件:
export class ParentComponent implements OnInit {
data;
....
onSearch(content: string) {
// do some staff here to filter the data and assign it to the property "data"
this.data = ....;
}
}
這是一個非常基本的示例,它可以幫助您更多地了解組件通過 Output 事件與其容器進行通信。
我建議您遵循 Angular 的官方文檔,該文檔將指導您開發示例應用程序並幫助您了解 Angular 框架的所有強大功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.