Angular4輸入屬性
輸入屬性通常用于父組件向子組件傳遞信息
舉個栗子:我們在父組件向子組件傳遞股票代碼,這里的子組件我們叫它app-order
首先在app.order.component.ts中聲明需要由父組件傳遞進來的值
order.component.ts
...@Input()stockCode: string@Input()amount: string...
order.component.html
<p>這里是子組件</p><p>股票代碼為{{stockCode}}</p><p>股票總數為{{amount}}</p>
然后我們需要在父組件(app.component)中向子組件傳值
app.component.ts
...stock: string...
app.component.html
<input type="text" placeholder="請輸入股票代碼" [(ngModel)]="stock"><app-order [stockCode]="stock" [amount]="100"></app-order>
這里我們使用了Angular的雙向數據綁定,將用戶輸入的值和控制器中的stock進行綁定。然后傳遞給子組件,子組件接收后在頁面顯示。
Angular4輸出屬性
當子組件需要向父組件傳遞信息時需要用到輸出屬性。
舉個栗子:當我們從股票交易所獲得股票的實時價格時,希望外部也可以得到這個信息。為了方便,這里的實時股票價格我們通過一個隨機數來模擬。這里的子組件我們叫它app.price.quote
使用EventEmitter從子組件向外發射事件
price.quote.ts
export class PriceQuoteComponent implements OnInit{ stockCode: string = 'IBM'; price: number; //使用EventEmitter發射事件 //泛型是指往外發射的事件是什么類型 //priceChange為事件名稱 @Output() priceChange:EventEmitter<PriceQuote> = new EventEmitter(); constructor(){ setInterval(() => { let priceQuote = new PriceQuote(this.stockCode, 100*Math.random()); this.price = priceQuote.lastPrice; //發射事件 this.priceChange.emit(priceQuote); }) } ngInit(){ }}//股票信息類//stockCode為股票代碼,lastPrice為股票價格export class PriceQuote{ constructor(public stockCode:string, public lastPrice:number )}
price.quote.html
<p> 這里是報價組件</p><p> 股票代碼是{{stockCode}}</p><p> 股票價格是{{price | number:'2.2-2'}}</p>
接著我們在父組件中接收事件
app.component.html
<app-price-quote (priceChange)="priceQuoteHandler($event)"></app-price-quote><p> 這是在報價組件外, 股票代碼是{{priceQuote.stokcCode}}, 股票價格是{{priceQuote.lastPrice | number:'2.2-2'}}</p>
事件綁定和原生的事件綁定是一樣的,都是將事件名稱放在()中。
app.component.ts
export class AppComponent{ priceQuote:PriceQuote = new PriceQuote('', 0); priceQuoteHandler(event:PriceQuote){ this.priceQuote = event; }}
這里的event類型就是子組件傳遞事件的類型。
angular4應用中輸入的最小值和最大值的方法
我有一個帶有表單的angular4應用程序.在這個我輸入一個百分比輸入.所以,我想用0到100之間的值來阻止輸入.
我試圖添加min =“0”和max =“100”,但我仍然可以輸入一個高于100或小于0的數字.
模板
<md-input-container> <input type="number" maxlength="3" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput"> <md-error>Required field</md-error></md-input-container>
你知道我怎么做嗎?
解決方法
我成功地使用了表單控件.
這是我的HTML代碼:
<md-input-container> <input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl"> <md-error>Please enter a value between 0 and 100</md-error> </md-input-container>
在我的打字稿代碼中,我有:
this.rateControl = new FormControl("",[Validators.max(100),Validators.min(0)])
因此,如果我們輸入的值大于100或小于0,則材料設計輸入變為紅色且該字段未驗證.所以之后,如果值不好,我點擊保存按鈕時就不保存.
總結
以上是武林網為你收集整理的angular4應用中輸入的最小值和最大值全部內容,希望文章能夠幫你解決angular4應用中輸入的最小值和最大值所遇到的程序開發問題。
新聞熱點
疑難解答