【问题标题】:value attribute not recognizable to parameter passed through Subject()通过 Subject() 传递的参数无法识别值属性
【发布时间】:2019-12-07 22:37:56
【问题描述】:

我在一个组件中有一个文本框,我希望在单击另一个组件中的按钮时将其值设为空白。假设有文本的组件叫CompA,有按钮的组件叫CompB。我在两个组件中都传递了一个服务,并在服务中创建了一个 Subject() (称为 abcService ),如下所示:

filterValuefeededToService = new Subject();

在 CompA 的 html 中,我在(输入)上做了一个模板引用和一个函数,如下所示:

<input type="text" #filtVal feedFilterTextVal(filtVal) />

在 CompA 的 ts 文件中,我做了:

feedFilterTextVal(filterValuefeeded) {
    console.log("filterValuefeeded", filterValuefeeded);
    this.abcService.filterValuefeededToService.next(
      filterValuefeeded
    );  

现在在 CompB 中,按钮在那里,我这样做:

this.abcService.filterValuefeededToService.subscribe(
            filterInput => {
              console.log("filterInput", filterInput);
            }
          );

我在filterInput 中获得了完整的输入。但是当我这样做时

console.log("filterInput value", filterInput.value);

出现错误:Property 'value' does not exist on type 'unknown'

所以我做了类似的事情:

this.abcService.filterValuefeededToService.subscribe(
            filterInput:HTMLInputElement => {
              console.log("filterInput", filterInput);
            }
          );

但它不起作用。请让我知道如何让CompB 识别它是一个 HTML 元素,以便我可以更改它的值。提前致谢。

【问题讨论】:

  • <input type="text" #filtVal feedFilterTextVal(filtVal) /> 不是模板的有效 Angular 语法。请阅读文档:angular.io/guide/template-syntax
  • Subject 是一个泛型类。由于您发出一个 HtmlInputElement,那应该是它的泛型类型。但你做的是倒退。 CompB 应该是发出事件的那个,并且 CompA 应该订阅以便将输入的模型设置为空字符串(从而清除它)。

标签: angular


【解决方案1】:

您应该像这样在abcService 中创建主题:

  mySubject = new Subject();
  value = "holamundo!";

然后从compB 按钮单击推送值到主题。

  constructor(private _myService: AbcServiceService) { }
  clickHandler(){
     let value = "";
     this._myService.mySubject.next(value);
  }

然后从compA读取主题的值并更新输入框。

constructor(private _myService:AbcServiceService) { }
inputValue;
ngOnInit() {
   console.log(this._myService.value)
   this.inputValue = this._myService.value;

   this._myService.mySubject.subscribe((data)=>{
      this.inputValue = data;
   })
}

工作演示:link

【讨论】:

  • 谢谢,但有一个问题。如果我在输入中输入任何其他内容然后单击按钮,它不会关闭
  • @gauravoberoi 修复了它,而不是值它应该是包含 的模板文件中的 ngModel
  • 谢谢,它正在工作。但是,如果我还想在点击按钮时保持输入焦点呢?
  • @gaurav oberoi 我认为不可能将注意力集中在输入上,因为当您单击按钮时,输入将失去焦点。如果它回答了您最初的问题以在将来帮助他人,请接受答案。
  • 你可能是对的。但我认为我们可以在单击按钮后专注于输入,这在 jquery 中也是可能的,并且是一种常见的功能。无论如何,我接受了你的回答。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 2018-07-31
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
相关资源
最近更新 更多