Javascript 用于 textarea 的 ngModel 在 angular 2 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37346820/
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 20:13:27  来源:igfitidea点击:

ngModel for textarea not working in angular 2

javascripthtmljsonangular

提问by Bhushan Gadekar

I am trying to print json object in textarea using ngModel.

我正在尝试使用 .json 在 textarea 中打印 json 对象ngModel

I have done following:

我做了以下工作:

<textarea style="background-color:black;color:white;" [(ngModel)]='rapidPage' rows="30" cols="120">                             
</textarea>

I want to load the json object in textarea. The above code is loading the rapidPageobject in textarea but its showing textarea value as [object Object].

我想在 textarea 中加载 json 对象。上面的代码rapidPage在 textarea 中加载对象,但它显示 textarea 值为[object Object].

object:

目的:

 this.rapidPage = {            
        "pageRows": [
            {
                "sections": [
                    {
                        "sectionRows": [
                            {
                                "secRowColumns": [                                       
                                ]
                            },
                            {
                                "secRowColumns": [
                                    {
                                        "colName": "users"
                                    }
                                ]
                            },
                            {
                                "secRowColumns": [
                                    {
                                        "colName": "sample"
                                    }
                                ]
                            }
                        ],
                        "width": 0
                    }
                ]
            }
        ],
        "pageName": "DefaultPage",
        "pageLayout": "DEFAULT_LAYOUT",
        "editMode": true
    };

I want to load the data as string. any inputs?

我想将数据加载为字符串。任何输入?

采纳答案by Ankit Singh

Assuming that you want to bind rapidPageas it is and will only write valid JSON in the textArea.

假设您想按rapidPage原样绑定并且只会在 textArea 中写入有效的 JSON。

  • You need to PARSEit when changing the value, and STRINGIFYwhen showing in textarea.
  • 您需要PARSE在更改值时以及STRINGIFY在 textarea 中显示时使用它。


StackBlitz DEMO

StackBlitz 演示

Do the following in your Component code

在您的组件代码中执行以下操作

  rapidPage = {"pageRows":[{"sections":[{"sectionRows":[{"secRowColumns":[]},{"secRowColumns":[{"colName":"users"}]},{"secRowColumns":[{"colName":"sample"}]}],"width":0}]}],"pageName":"DefaultPage","pageLayout":"DEFAULT_LAYOUT","editMode":true}; 
  // your object

  get rapidPageValue () {
    return JSON.stringify(this.rapidPage, null, 2);
  }

  set rapidPageValue (v) {
    try{
    this.rapidPage = JSON.parse(v);}
    catch(e) {
      console.log('error occored while you were typing the JSON');
    };
  }

Template Usage:

模板用法:

<textarea [(ngModel)]='rapidPageValue' rows="30" cols="120">                             
</textarea>

回答by Hasnain Ali Sohrani

<textarea class="form-control" 
          name="message"
          rows="8"
          [(ngModel)]="Obj.message"
          #message='ngModel'
          ></textarea>

for Two way binding You just need to add attribute in textarea tag name="message", ONLY [(ngModel)]works 100%!.

对于双向绑定您只需要在 textarea 标签中添加属性name="message",仅[(ngModel)]100% 有效!。

回答by Markus Brunner

For binding textarea values in Angular 2 you can use the change-function:

要在 Angular 2 中绑定 textarea 值,您可以使用更改功能:

Template

模板

<textarea id="some-value" (change)="doTextareaValueChange($event)">{{textareaValue}}</textarea>

Component

成分

export class AppComponent implements OnInit {
  private textareaValue = '';
  doTextareaValueChange(ev) {
    try {
      this.textareaValue = ev.target.value;
    } catch(e) {
      console.info('could not set textarea-value');
    }
  }
}

回答by windmaomao

Unless you really want to have sync in between, you would normally implement a button to save/apply the change when it's finished json editing. If that is the case, your render is easy.

除非您真的希望在两者之间进行同步,否则您通常会在完成 json 编辑后实现一个按钮来保存/应用更改。如果是这种情况,您的渲染很容易。

<textarea #textbox>{{ rapidPage | json }}</textarea>

Make sure no other space or return character in between the above line.

确保上面的行之间没有其他空格或返回字符。

Then an traditional button, ex.

然后是一个传统的按钮,例如。

<a (click)="updateRapidPage(textbox.value)">Apply</a>

I found this is better in some case than brutal [(rapidPage)].

我发现这在某些情况下比残酷更好[(rapidPage)]

You can also use @ViewChild('textbox') inputinside the component to access this variable.

您还可以@ViewChild('textbox') input在组件内部使用来访问此变量。

回答by Oscar Adrian Luevano Cadena

Can you test with this:

你能用这个测试吗:

<textarea #textbox (change)="text = textbox.value" style="width:100%;">{{ text }}</textarea>

Regards

问候

回答by Anand Rockzz

ngModel works if

ngModel 工作,如果

  1. There is a form wrapped around it & textarea has a name attribute added to it.
  1. 有一个围绕它的表单 & textarea 添加了一个 name 属性。

If you not you can use the following syntax to achieve the same effect

如果没有,您可以使用以下语法来达到相同的效果

<textarea [value]="strVariableInComponent" (input)="strVariableInComponent = $event.target.value;"></textarea>

回答by mattyman

As per documentation [()] is for two way syntax sugar to remove the boilerplate. What event is being invoked at this? Irrespective, you can put a string output also alongwith the event in below code

根据文档 [()] 是用于删除样板的两种语法糖。这里正在调用什么事件?无论如何,您也可以在下面的代码中将字符串输出与事件一起放置

Probably try the below code implemetation for your string output

可能会为您的字符串输出尝试以下代码实现

@Directive({
  selector: '[ngModel]',
  host: {
    "[value]": 'ngModel',
    "(input)": "ngModelChange.next($event.target.value)"
  }
})
class NgModelDirective {
  @Input() ngModel:any; // stored value
  @Output() ngModelChange:EventEmitter; = new EventEmitter() // an event emitter
}

回答by Pardeep Jain

You can stringifyyour json and use in the ngModel like this -

你可以stringify像这样在 ngModel 中使用你的 json 和使用 -

<textarea style="height:100px; width:300px;background-color:black;color:white;" [(ngModel)]='rapidPage' rows="30" cols="120">
    </textarea>

ArrayDemo: Array<any> = [{"name":"pardeep","last":"jain"}]
  rapidPage = JSON.stringify(this.ArrayDemo);

Working Example Working Example

工作示例 Working Example

Browser shows [object object]because angular unables to parse the JSON the asign the value in ngModel you must need a string so convert this using JSON.stringify

浏览器显示,[object object]因为 angular 无法解析 JSON,所以在 ngModel 中指定值,您必须需要一个字符串,因此使用JSON.stringify