迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > Angular >

在 Angular 中使用 @Input()

作者:迹忆客 最近更新:2023/05/09 浏览次数:

这篇文章是关于 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() 需要三个步骤:

  1. @Input() 添加到 HTML 元素。
  2. ng-model 属性添加到要与输入绑定的元素。
  3. 为控制器中的 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>

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便