Javascript Angular2 - 组件变量/组件类属性上的双向数据绑定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35639650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:03:46  来源:igfitidea点击:

Angular2 - two way databinding on a component variable / component class property?

javascriptangulardata-binding2-way-object-databinding

提问by DanAbdn

In Angular2 (Beta 6) I have a component for a main menu.

在 Angular2(Beta 6)中,我有一个主菜单组件。

<mainmenu></mainmenu>

I want to bind a boolean for wide or narrow. So I made it into this:

我想为宽或窄绑定一个布尔值。所以我把它变成了这样:

<mainmenu [(menuvisible)]="true"></mainmenu>

But what I want (I think) is to bind to a javascript class property (as I may have other things to bind but want to be tidy by using a single class in the component).

但是我想要(我认为)是绑定到 javascript 类属性(因为我可能还有其他要绑定的东西,但希望通过在组件中使用单个类来保持整洁)。

I get an error

我收到一个错误

EXCEPTION: Template parse errors: Invalid property name 'menumodel.visible' ("

][(menumodel.visible)]="menumodel.visible">

例外:模板解析错误:无效的属性名称“menumodel.visible”(“

][(menumodel.visible)]="menumodel.visible">

If I try the same with a single variable instead of a class I get:

如果我对单个变量而不是类进行相同的尝试,我会得到:

Template parse errors: Parser Error: Unexpected token '='

模板解析错误:解析器错误:意外标记“=”

However this (one way binding?) does seem to work (but I might want to trigger the menu to go wide/narrow from another component so felt this should be a two-way data bound property):

然而,这(单向绑定?)似乎确实有效(但我可能想触发菜单从另一个组件变宽/变窄,所以觉得这应该是一个双向数据绑定属性):

<menu [vis]="true"></menu>

This is a bit of my menu component:

这是我的菜单组件的一部分:

@Component({
    selector: 'menu',
    templateUrl: './app/menu.html',
    providers: [HTTP_PROVIDERS, ApplicationService],
    directives: [ROUTER_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgForm]
})
export class MenuComponent implements OnInit {

    mainmenu: MainMenuVM;

    constructor(private _applicationService: ApplicationService) {
        this.mainmenu = new MainMenuVM();
    }

    // ...ngOnInit, various functions

}

Here is my MainMenu View Model class

这是我的 MainMenu View Model 类

export class MainMenuVM {
    public visible: boolean;
    constructor(
    ) { this.visible = true; }
}

I'm trying to create a menu which has icons and text, but can go narrow to just show icons. I will emit this event upwards to a parent component to alter the position of the container next to the menu. Triggering a content container to maximised will trigger the menu to go narrow - I am not saying this is the best way, but I would like to resolve this particular question before going deeper.

我正在尝试创建一个包含图标和文本的菜单,但可以缩小到仅显示图标。我会将此事件向上发送到父组件以更改菜单旁边容器的位置。触发内容容器最大化将触发菜单变窄 - 我并不是说这是最好的方法,但我想在深入研究之前解决这个特定问题。

Please note: I am not databinding to an input control here - just databinding to a component so I can then modify the UI.

请注意:我不是在这里对输入控件进行数据绑定 - 只是对组件进行数据绑定,以便我可以修改 UI。

This is from the Angular cheatsheet

这是来自 Angular 备忘单

<my-cmp [(title)]="name">   
Sets up two-way data binding. Equivalent to: <my-cmp [title]="name" (titleChange)="name=$event">

Thanks in advance!

提前致谢!

UPDATE

更新

Integrating the code from the accepted answer and adapting for my particular use case here the final working code:

从接受的答案中集成代码并在此处适应我的特定用例,最终工作代码:

app.html

应用程序.html

...header html content

// This is what I started with
<!--<menu [menuvisible]="true" (menuvisibleChange)="menuvisible=$event"></menu>-->

// This is two way data binding
// 1. Banana-in-a-box is the input parameter
// 2. Banana-in-a-box is also the output parameter name (Angular appends it's usage with Change in code - to follow shortly)
// 3. Banana-in-a-box is the short hand way to declare the commented out code
// 4. First parameter (BIAB) refers to the child component, the second refers the variable it will store the result into.
// 5. If you just need an input use the remmed out code with just the first attribute / value
<menu [(menuvisible)]="menuvisible"></menu>

.. div content start 
<router-outlet></router-outlet>
.. div content end 

app.component.ts (root)

app.component.ts(根)

export class AppComponent implements OnInit{
   menuvisible: Boolean;
}

menu.component.ts (child of root)

menu.component.ts(根的孩子)

export class MenuComponent implements OnInit {
    // Parameters - notice the appending of "Change"
    @Input() menuvisible: boolean;
    @Output() menuvisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();

    // Init
    ngOnInit() {
        // Populate menu - fetch application list       
        this.getApplications();

        // Initially we want to show/hide the menu depending on the input parameter
        (this.menuvisible === true) ? this.showMenu() : this.hideMenu();
    }

    //...more code
}

menu.html

菜单.html

<div id="menu" [ngClass]="menuStateClass" style="position: absolute; top:0px; left: 0px;z-index: 800; height: 100%; color: #fff; background-color: #282d32">
    <div style="margin-top: 35px; padding: 5px 0px 5px 0px;">

        <ul class="menuList" style="overflow-x: hidden;">
            <li>IsMenuVisible:{{menuvisible}}</li>
            <li style="border-bottom: 1px solid #3d4247"><a (click)="toggleMenu()"><i class="fa fa-bars menuIcon" style="color: white; font-size: 16px;"></i></a></li>
            <li *ngFor="#app of applications">
                <a [routerLink]="[app.routerLink]">
                    <i class="menuIcon" [ngClass]="app.icon" [style.color]="app.iconColour" style="color: white;"></i>
                    <span [hidden]="menuStateTextHidden">{{ app.name }}</span>
                </a>
            </li>
        </ul>

    </div>
</div>

Remember to import what you need e.g.

记得导入你需要的东西,例如

import {Component, EventEmitter, OnInit, Input, Output} from 'angular2/core';

从“angular2/core”导入{Component、EventEmitter、OnInit、Input、Output};

Highly recommend this video on You Tube: Angular 2 Tutorial (2016) - Inputs and Outputs

在 You Tube 上强烈推荐此视频: Angular 2 教程 (2016) - 输入和输出

回答by Günter Z?chbauer

For two-way binding you need something like:

对于双向绑定,您需要类似的东西:

@Component({
    selector: 'menu',
    template: `
<button (click)="menuvisible = !menuvisible; menuvisibleChange.emit(menuvisible)">toggle</button>
<!-- or 
   <button (click)="toggleVisible()">toggle</button> -->
`,
    // HTTP_PROVIDERS should now be imports: [HttpModule] in @NgModule()
    providers: [/*HTTP_PROVIDERS*/, ApplicationService],
    // This should now be added to declarations and imports in @NgModule()
    // imports: [RouterModule, CommonModule, FormsModule]
    directives: [/*ROUTER_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgForm*/]
})
export class MenuComponent implements OnInit {
    @Input() menuvisible:boolean;
    @Output() menuvisibleChange:EventEmitter<boolean> = new EventEmitter<boolean>();

    // toggleVisible() {
    //   this.menuvisible = !this.menuvisible;       
    //   this.menuvisibleChange.emit(this.menuvisible);
    // }
}

And use it like

并使用它

@Component({
  selector: 'some-component',
  template: `
<menu [(menuvisible)]="menuVisibleInParent"></menu>
<div>visible: {{menuVisibleInParent}}</div>
`
  directives: [MenuComponent]
})
class SomeComponent {
  menuVisibleInParent: boolean;
}

回答by squadwuschel

I've created a short plunkr.

我创建了一个简短的 plunkr。

ngModel Like Two-Way-Databinding for components

ngModel 类似于组件的双向数据绑定

You have at least two possibilities to to create a two way databinding for components

您至少有两种可能性可以为组件创建双向数据绑定

V1: With ngModel Like Syntax, there you have to create a @Output property with the same name line the @Input property + "Change" at the end of the @Output property name

V1:使用ngModel Like Syntax,您必须在@Output 属性名称末尾创建一个具有相同名称的@Output 属性行@Input 属性+“Change”

@Input() name : string;
@Output() nameChange = new EventEmitter<string>(); 

with V1 you can now bind to the Child Component with the ngModel Syntax

使用 V1,您现在可以使用 ngModel 语法绑定到子组件

[(name)]="firstname"

V2. Just create one @Input and @Output property with the naming you prefer

V2. 只需使用您喜欢的命名创建一个 @Input 和 @Output 属性

@Input() age : string;
@Output() ageChanged = new EventEmitter<string>();

with V2 you have to create two attributes to get the two way databinding

使用 V2,您必须创建两个属性才能获得双向数据绑定

[age]="alter" (ageChanged)="alter = $event"

Parent Component

父组件

import { Component } from '@angular/core';

@Component({
   selector: 'my-app',
   template: `<p>V1 Parentvalue Name: "{{firstname}}"<br/><input [(ngModel)]="firstname" > <br/><br/>
              V2 Parentvalue Age: "{{alter}}" <br/><input [(ngModel)]="alter"> <br/><br/>

              <my-child [(name)]="firstname" [age]="alter" (ageChanged)="alter = $event"></my-child></p>`
})
export class AppComponent { 
    firstname = 'Angular'; 
    alter = "18"; 
}

Child Component

子组件

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
   selector: 'my-child',
   template: `<p>V1 Childvalue Name: "{{name}}"<br/><input [(ngModel)]="name" (keyup)="onNameChanged()"> <br/><br/>
              <p>V2 Childvalue Age: "{{age}}"<br/><input [(ngModel)]="age"  (keyup)="onAgeChanged()"> <br/></p>`
 })
export class ChildComponent { 
     @Input() name : string;
     @Output() nameChange = new EventEmitter<string>();

     @Input() age : string;
     @Output() ageChanged = new EventEmitter<string>();

     public onNameChanged() {
         this.nameChange.emit(this.name);
     }

     public onAgeChanged() {
         this.ageChanged.emit(this.age);
     }
 }