How to make ngIf work after transclusion?
Asked Answered
H

1

8

I have a list component where I want to define custom columns inside. These columns get transcluded into the row of the components template. Unfortunately I can't use ngIf in this context.

Here is my $postLink function of the myList component:

const template = $templateCache.get('myList.tpl.html');
const jqTemplate = angular.element(template);
const row = angular.element(jqTemplate.children()[0]);

$transclude(clone => {
  row.append(clone);
  $element.html(jqTemplate.html());
});

$compile($element.contents())($scope);

Here is a plnkr of the minimal sample: http://plnkr.co/edit/C9Rvs8NiTYsV3pwoPF6a

Is that because of the terminal property? Can someone entlighten me why ngIf does not work like expect it to?

Headcheese answered 3/4, 2018 at 1:48 Comment(2)
Check this kylelieber.com/2016/04/angular-transclude-directive-and-ng-if (A component is an special type of directive, so the article still valid). I know that you are asking for ng-if, but your case works with a ng-show/hide. Obviously remove the dom elements and its watchers is not the same than only hidden them by css in terms of performance, but if you don't have a huge amout of rows/cols, maybe you could save a headache :)Daredevil
Your link actually fixed the whole issue, that's a really nice work around you have there, time to save it :-)Pinette
E
0

I think trying to perform the operation in postLink phase is too late, since it is first being applied to child elements.

Compile phase seems to be more appropriate. In there things are simpler, you don't even need to use transclusion or clone-linking function. Scope is applied at a later state.

I provide a solution using directive since in cases like this I find component syntax more confusing.

app.directive('myList', function($templateCache){
    return {
        bindings: {
          list: '='
        },
        transclude: false,
        compile: function(tElement) {
            const template = $templateCache.get('myList.tpl.html');
            const jqTemplate = angular.element(template);
            var elemChildren = tElement.children('div');
            jqTemplate.children('.row').append(elemChildren);
            tElement.append(jqTemplate);
          return {};
        }

    }

});

http://plnkr.co/edit/MrLJmnMKxO8PVPkzE8KK?p=preview

Ecclesiology answered 16/4, 2018 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.