How to access a custom item in a knockout component?

Take a look at this scenario:

ko.components.register('hello', { viewModel: function() { }, template: "<h1>hello wrold</h1>" }); 

If I use <hello></hello> , the generated html result will be:

 <hello><h1>hello world</h1></hello> 

But what if I want this:

 <hello class="hello"><h1>hello world</h1></hello> 

Then how can I get the link to the tag of the user element in the component?

+6
source share
1 answer

A user element contains a component; it is not considered part of it. As well as the external tag used in binding foreach , template or with . If you want to style this tag, you need to add anchors for its style. The component will populate its contents.

 <hello data-bind="css: 'hello'"></hello> 

However, if you absolutely wanted to access the parent element, I assume that this is possible, but I would not recommend it. The component should only care about itself, and not about the container that contains it. This can (and will) cause problems if the element had any child nodes that also had bindings.

Use the factory function for your view model. It will have access to component information (which currently only includes the containing element )

 ko.components.register('hello', { viewModel: { createViewModel: function (params, componentInfo) { var element = componentInfo.element; ko.applyBindingsToNode(element, { css: 'hello' }); return {}; } }, template: "<h1>hello world</h1>" }); 
+11
source

Source: https://habr.com/ru/post/975225/


All Articles