在 Angular 中使用 @Input()

Muhammad Adil 2023年1月30日
  1. Angular 中的 @Input() 指令
  2. 在 Angular 应用程序中使用 @Input() 的步骤
在 Angular 中使用 @Input()

这篇文章是关于 Angular @Input(),Angular 中使用的一个函数,用于从用户那里获取输入,然后在程序中使用它进行处理。也可以使用此函数读取文件并从外部 API 获取数据。

Angular 中的 @Input() 指令

顾名思义,@Input() 指令用于输入字段。 @Input() 最适合在表单字段和文本框中捕获用户输入。

当用户输入信息时,它会自动更新字段或文本框的值。它还接受来自其他输入和 ngModelOptions 的值以自动更新其值。

@Input() 指令具有三个属性:typenamevalue

  • type 属性指定要创建的输入字段类型。
  • name 属性指定输入字段的 id,并将在 JavaScript 代码中用作其名称。
  • 如果你创建未设置默认值的文本输入字段,则需要 value 属性。

以下是输入字段的有效类型列表:

  • Text
  • Password
  • Email Address
  • Number
  • Date Picker (Date)
  • Time Picker (Time)
  • Range Slider (Range)
  • Checkbox (Checkbox)

要使用 @Input(),你需要将其作为指令添加到所需的 HTML 元素上。

@Input() 用于将数据从父组件传输到子组件,而@Output() 用于将数据从子组件传递到父组件。 @Input() 的一个典型例子是询问用户的年龄。

以下代码将显示询问用户年龄的提示,然后将其返回给调用函数,调用函数将其分配给一个名为 age 的变量。

var age = Input("Please enter your age");

在 Angular 应用程序中使用 @Input() 的步骤

在 Angular 应用程序中使用 @Input() 需要三个步骤:

  • @Input() 添加到 HTML 元素。
  • ng-model 属性添加到要与输入绑定的元素。
  • 为控制器中的 ng-model 属性分配一个表达式。

TypeScript 代码:

import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    isFocusStyle = false;
    type = 'INFO';
    onFocus() {
        this.isFocusStyle = true;
        this.type = 'INFO';
    }
    onEnter() {
        this.isFocusStyle = false;
        const input = document.querySelector('input');
    }
}

HTML 代码:

<h1>Example of Angular Input</h1>
<div class="input-wrapper" [ngClass]="{'focus-style': isFocusStyle}">
    <input type="test" placeholder=" Write " (focus)="onFocus()">
</div>

点击这里查看上述代码的演示。

作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

相关文章 - Angular Input