我創建了一個私有的 npm 包,我可以使用 html 中的以下代碼在我的其他應用程式中運行它:
<app-header-name></app-header-name>
這是它運行的 npm 包中的代碼:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header-name',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
public blob: any;
constructor() {}
ngOnInit(): void {
console.log(this.blob);
}
}
這是 npm 包中的 html 代碼:
<div class="row">
<div class="col d-flex justify-content-center">
Click the button to download the template
</div>
</div>
我的問題是,如何將應用程式中的變數傳遞到 npm 包中的變數 blob 中?我嘗試了以下操作,它只是控制臺記錄了“未定義”:
<app-header-name blob="bazinga"></app-header-name>
另外,有沒有辦法從 npm 包中傳回資料?例如,它將接收字串 blob 變數,然后向其中添加另一個單詞并將其傳遞回主應用程式?
uj5u.com熱心網友回復:
您需要在組件中添加一個輸入。
import { Component, EventEmitter, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-header-name',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
@Input() blob: any;
@Output() somethingOut = new EventEmitter();
ngOnInit(): void {
console.log(this.blob);
}
sendToParent() {
this.somethingOut.emit({ data: 'Hello from child component '});
}
}
傳入一個字串
<app-header-name blob="bazinga"></app-header-name>
從父級傳入一個變數
<app-header-name [blob]="someVarOnTheParent"></app-header-name>
傳入和傳出一個變數,父組件需要一個函式來接收資料。請注意$event是必需的,因為孩子正在傳遞資料
<app-header-name [blob]="someVarOnTheParent" (somethingOut)="parentFunc($event)"></app-header-name>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341745.html
標籤:javascript 节点.js 有角的 打字稿 新产品经理
上一篇:正則運算式驗證10位電話號碼
